
上QQ阅读APP看书,第一时间看更新
2.6 任务实现
本任务将实现使用BeautifulSoup库、lxml库和requests库完成对百度标题的爬取和解析任务。
1)在Python文件中导入requests库和BeautifulSoup库。

2)使用requests.get()方法获得指定页面数据。

3)由于requests对象的默认编码方式不是utf-8,因此可能导致乱码,所以先设置requests.encoding='utf-8'。

4)在BeautifulSoup中使用lxml作为解析器,解析request.text得到的页面数据。

5)输出指定的页面标签文本。这里介绍两种方式。
① 直接使用需要查找的标签名。

② 使用select方法选择需要查找的标签路径。

标签路径可以通过浏览器的开发者工具获取。其具体获取方法是:打开指定页面后,按〈F12〉键,打开开发者工具,选择指定的页面元素并右击,在弹出的快捷菜单中选择“Copy”→ “Copy selector”命令,如图2-15所示。

图2-15 获得页面元素标签路径
6)显示结果如图2-17所示。

图2-17 标签查询结果显示
这样就使用requests库和BeautifulSoup库成功地抓取了百度页面中标签为<title>的文本内容。本任务的完整代码如下。
