
2.4 使用Beautiful Soup解析网页
通过requests库已经抓取到网页源码,接下来要从源码中找到并提取数据。Beautiful Soup是Python的一个库,其主要功能是从网页中抓取数据。Beautiful Soup目前已经被移植到bs4库中,也就是说在导入Beautiful Soup时需要先安装bs4库。安装bs4库的方式如图2-18所示。

图2-18
安装好bs4库以后,还需安装lxml库。如果我们不安装lxml库,就会使用 Python默认的解析器。尽管Beautiful Soup既支持Python标准库中的HTML解析器,又支持一些第三方解析器,但是lxml库功能更强大、速度更快,因此笔者推荐安装lxml库。安装Python第三方库后,输入下面的代码,即可开启Beautiful Soup之旅。

代码运行结果如图2-19所示。
Beautiful Soup库能够轻松解析网页信息,它被集成在bs4库中,需要时可以从bs4库中调用。其表达语句如下。


图2-19
首先,HTML文档将被转换成Unicode编码格式,然后Beautiful Soup选择最合适的解析器来解析这个文档,此处指定lxml库进行解析。解析后便将复杂的HTML文档转换成树形结构,并且每个节点都是Python对象。这里将解析后的文档存储到新建的变量soup中,代码如下。

接下来用select(选择器)定位数据,在定位数据时需要使用浏览器的开发者模式,将鼠标光标停留在对应的数据位置并右击,在弹出的快捷菜单中选择“检查”命令,如图2-20所示。

图2-20
随后在浏览器右侧会弹出开发者界面,右侧高亮的代码(见图2-21(b))对应着左侧高亮的数据文本(见图2-21(a))。右击右侧高亮的代码,在弹出的快捷菜单中选择“Copy”g“Copy selector”命令,便可以自动复制路径。

图2-21
将路径粘贴到文档中,代码如下。

由于这条路径是选中的第一条新闻的路径,而我们需要获取所有的头条新闻,因此将li:nth-child(1)中冒号(包含冒号)后面的部分删掉,代码如下。

使用soup.select引用这个路径,代码如下。
