准备工作:安装requests和BeautifulSoup4。打开cmd,输入如下命令
pip install requests pip install BeautifulSoup4
打开我们要爬取的页面,这里以新浪新闻为例,地址为:http://news.sina.com.cn/china/
按F12打开开发人员工具,点击左上角的图片,然后再页面中点击你想查看的元素:
我点击了新闻标题处的元素,查看到该元素为class=news-item的元素:
在这里,我们要获取新闻的时间,标题和链接,查看到分别在如下位置:
现在,就可以根据元素的结构编写爬虫代码了:
import requests from bs4 import BeautifulSoup url = 'http://news.sina.com.cn/china/' res = requests.get(url) # 使用UTF-8编码 res.encoding = 'UTF-8' # 使用剖析器为html.parser soup = BeautifulSoup(res.text, 'html.parser') #遍历每一个class=news-item的节点 for news in soup.select('.news-item'): h2 = news.select('h2') #只选择长度大于0的结果 if len(h2) > 0: #新闻时间 time = news.select('.time')[0].text #新闻标题 title = h2[0].text #新闻链接 href = h2[0].select('a')[0]['href'] #打印 print(time, title, href)
运行程序,结果如下图所示: