Python爬虫实践:从网页抓取特定数据案例

原创 蔚落 2025-02-22 14:24 57阅读 0赞

在Python中,我们可以使用各种库来抓取网页上的特定数据。这里我们将介绍一个常见的例子——抓取网站新闻内容。

首先,我们需要安装两个库:requestsBeautifulSoup4

  1. pip install requests beautifulsoup4

然后,我们编写代码来抓取新闻内容:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. # 指定要爬取的网站URL
  4. url = 'https://example.com/news' # 替换为你需要爬取的实际链接
  5. response = requests.get(url) # 发送GET请求
  6. if response.status_code == 200: # 检查状态码是否为200,表示请求成功
  7. soup = BeautifulSoup(response.text, 'html.parser') # 解析HTML内容
  8. news_list = soup.find_all('div', class_='news-item')) # 找到所有新闻条目(一般情况下是class)
  9. for item in news_list:
  10. title = item.find('h2').text.strip() # 提取新闻标题
  11. content = item.find('p').text.strip() # 提取新闻内容
  12. print(f'Title: {title}')
  13. print(f'Content: {content}\n')
  14. else: # 状态码不是200,表示请求失败或网页不存在
  15. print('Failed to fetch news. Check the URL and try again.')

这个示例抓取了一个新闻网站的新闻标题和内容。你可以根据需要调整代码,爬取不同的网站数据。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,57人围观)

还没有评论,来说两句吧...

相关阅读