Python3爬虫教程:PyQuery详解!

PyQuery 简介

PyQuery 用于对 XML 文档进行操作,比如:查询 XML 文档中的某个元素,获取某个元素的属性等。它的 API 和前端著名框架 jQuery 相似,名字的由来也是基于此。(官方介绍:pyquery: a jquery-like library for python)

安装

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">$ pip3 install pyquery

</pre>

加载 XML 文档

pyquery 提供了三种 XML 加载方式:

从字符串中加载;

从 url 加载;

从文件加载;

这里,我们一般使用 Requests 获取网络资源数据,接着,使用 pyquery 从字符串中加载数据。

这样做的理由是,Requests 作为一个专门的网络库,有较强的定制能力。

简单看下示例代码:

查询元素

查询元素的核心点是 CSS 选择器(CSS Selector),大家可以通过搜索引擎查找相关资料。

Tip

PyQuery 支持手动选择解析器(parser),如下:

<pre style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;">pq('<html><body><p>toto</p></body></html>', parser='xml')

</pre>

parse 的取值是:

xml

html

html5

soup

html_fragments

默认使用的是 lxml 的 xml 解析器,一般不需要手动选择。这里只是作为一个小知识点提及。

源码视频书籍练习题等资料进群696541369 即可免费获取

更多python记得关注我的公众号 从0到1Python之路

猜你喜欢

转载自blog.csdn.net/weixin_42209553/article/details/86656648
今日推荐