python3爬虫-爬取新浪新闻首页所有新闻标题

超、凢脫俗 2022-07-12 09:21 482阅读 0赞

准备工作:安装requests和BeautifulSoup4。打开cmd,输入如下命令

  1. pip install requests
  2. pip install BeautifulSoup4

打开我们要爬取的页面,这里以新浪新闻为例,地址为:http://news.sina.com.cn/china/

按F12打开开发人员工具,点击左上角的图片,然后再页面中点击你想查看的元素:

image\_1b9cn3qf33l8r6s1skf1duh1ann9.png-104.2kB

我点击了新闻标题处的元素,查看到该元素为class=news-item的元素:

image\_1b9cn61ap1qc62f57l5isu60m.png-288.5kB

在这里,我们要获取新闻的时间,标题和链接,查看到分别在如下位置:

image\_1b9cnc13h1es5tc31iif1a261adr13.png-98.6kB

现在,就可以根据元素的结构编写爬虫代码了:

  1. import requests
  2. from bs4 import BeautifulSoup
  3. url = 'http://news.sina.com.cn/china/'
  4. res = requests.get(url)
  5. # 使用UTF-8编码
  6. res.encoding = 'UTF-8'
  7. # 使用剖析器为html.parser
  8. soup = BeautifulSoup(res.text, 'html.parser')
  9. #遍历每一个class=news-item的节点
  10. for news in soup.select('.news-item'):
  11. h2 = news.select('h2')
  12. #只选择长度大于0的结果
  13. if len(h2) > 0:
  14. #新闻时间
  15. time = news.select('.time')[0].text
  16. #新闻标题
  17. title = h2[0].text
  18. #新闻链接
  19. href = h2[0].select('a')[0]['href']
  20. #打印
  21. print(time, title, href)

运行程序,结果如下图所示:

image\_1b9cndiud9cs1oleisart8hb61g.png-201.9kB

发表评论

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

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

相关阅读