前言

你是否觉得 XPath 的用法多少有点晦涩难记呢?

你是否觉得 BeautifulSoup 的语法多少有些悭吝难懂呢?

你是否甚至还在苦苦研究正则表达式却因为少些了一个点而抓狂呢?

你是否已经有了一些前端基础了解选择器却与另外一些奇怪的选择器语法混淆了呢?

嗯,那么,前端大大们的福音来了,PyQuery 来了,乍听名字,你一定联想到了 jQuery,如果你对 jQuery 熟悉,那么 PyQuery 来解析文档就是不二之选!包括我在内!

PyQuery 是 Python 仿照 jQuery 的严格实现。语法与 jQuery 几乎完全相同,所以不用再去费心去记一些奇怪的方法了。

天下竟然有这等好事?我都等不及了!

安装

有这等神器还不赶紧安装了!来!

 
1
pip install pyquery

还是原来的配方,还是熟悉的味道。

参考来源

本文内容参考官方文档,更多内容,大家可以去官方文档学习,毕竟那里才是最原汁原味的。

目前版本 1.2.4 (2016/3/24)

官方文档

简介

pyquery allows you to make jquery queries on xml documents. The API is as much as possible the similar to jquery. pyquery uses lxml for fast xml and html manipulation.

This is not (or at least not yet) a library to produce or interact with javascript code. I just liked the jquery API and I missed it in python so I told myself “Hey let’s make jquery in python”. This is the result.

It can be used for many purposes, one idea that I might try in the future is to use it for templating with pure http templates that you modify using pyquery. I can also be used for web scrapping or for theming applications with Deliverance.

pyquery 可让你用 jQuery 的语法来对 xml 进行操作。这I和 jQuery 十分类似。如果利用 lxml,pyquery 对 xml 和 html 的处理将更快。

这个库不是(至少还不是)一个可以和 JavaScript交互的代码库,它只是非常像 jQuery API 而已。

初始化

在这里介绍四种初始化方式。

(1)直接字符串

 
1
2
from pyquery import PyQuery as pq
doc = pq("<html></html>")

pq 参数可以直接传入 HTML 代码,doc 现在就相当于 jQuery 里面的 $ 符号了。

(2)lxml.etree

 
1
2
from lxml import etree
doc = pq(etree.fromstring("<html></html>"))

可以首先用 lxml 的 etree 处理一下代码,这样如果你的 HTML 代码出现一些不完整或者疏漏,都会自动转化为完整清晰结构的 HTML代码。

(3)直接传URL

 
1
2
from pyquery import PyQuery as pq
doc = pq('http://www.baidu.com')

这里就像直接请求了一个网页一样,类似用 urllib2 来直接请求这个链接,得到 HTML 代码。

(4)传文件

 
1
2
from pyquery import PyQuery as pq
doc = pq(filename='hello.html')

可以直接传某个路径的文件名。

快速体验

现在我们以本地文件为例,传入一个名字为 hello.html 的文件,文件内容为

 
1
2
3
4
5
6
7
8
9
<div>
    <ul>
         <li class="item-0">first item</li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
         <li class="item-1 active"><a href="link4.html">fourth item</a></li>
         <li class="item-0"><a href="link5.html">fifth item</a></li>
     </ul>
</div>

编写如下程序

 
1
2
3
4
5
6
7
from pyquery import PyQuery as pq
doc = pq(filename='hello.html')
print doc.html()
print type(doc)
li = doc('li')
print type(li)
print li.text()

运行结果

 
1
2
3
4
5
6
7
8
9
10
11
    <ul>
         <li class="item-0">first item</li>
         <li class="item-1"><a href="link2.html">second item</a></li>
         <li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
         <li class="item-1 active"><a href="link4.html">fourth item</a></li>
         <li class="item-0"><a href="link5.html">fifth item</a></li>
     </ul>
 
<class 'pyquery.pyquery.PyQuery'>
<class 'pyquery.pyquery.PyQuery'>
first item second item third item fourth item fifth item

看,回忆一下 jQuery 的语法,是不是运行结果都是一样的呢?

在这里我们注意到了一点,PyQuery 初始化之后,返回类型是 PyQuery,利用了选择器筛选一次之后,返回结果的类型依然还是 PyQuery,这简直和 jQuery 如出一辙,不能更赞!然而想一下 BeautifulSoup 和 XPath 返回的是什么?列表!一种不能再进行二次筛选(在这里指依然利用 BeautifulSoup 或者 XPath 语法)的对象!

然而比比 PyQuery,哦我简直太爱它了!

属性操作

你可以完全按照 jQuery 的语法来进行 PyQuery 的操作。

 
1
2
3
4
5
6
from pyquery import PyQuery as pq
 
p = pq('<p id="hello" class="hello"></p>')('p')
print p.attr("id")
print p.attr("id", "plop")
print p.attr("id", "hello")

运行结果

 
1
2
3
hello
<p id="plop" class="hello"/>
<p id="hello" class="hello"/>

再来一发

 
1
2
3
4
5
6
7
from pyquery import PyQuery as pq
 
p = pq('<p id="hello" class="hello"></p>')('p')
print p.addClass('beauty')
print p.removeClass('hello')
print p.css('font-size', '16px')
print p.css({'background-color': 'yellow'})

运行结果

 
1
2
3
4
<p id="hello" class="hello beauty"/>
<p id="hello" class="beauty"/>
<p id="hello" class="beauty" style="font-size: 16px"/>
<p id="hello" class="beauty" style="font-size: 16px; height: inherit; font-size: inherit !important; line-height: inherit !important; font-weight: inherit !important; color: rgb(0, 111, 224) !important;">/>

依旧是那么优雅与自信!

在这里我们发现了,这是一连串的操作,而 p 是一直在原来的结果上变化的。

因此执行上述操作之后,p 本身也发生了变化。

DOM操作

同样的原汁原味的 jQuery 语法

 
1
2
3
4
5
6
7
8
9
10
11
from pyquery import PyQuery as pq
 
p = pq('<p id="hello" class="hello"></p>')('p')
print p.append(' check out <a href="http://reddit.com/r/python"><span>reddit</span></a>')
print p.prepend('Oh yes!')
d = pq('<div class="wrap"><div id="test"><a href="http://cuiqingcai.com">Germy</a></div></div>')
p.prependTo(d('#test'))
print p
print d
d.empty()
print d

运行结果

 
1
2
3
4
5
<p id="hello" class="hello"> check out <a href="http://reddit.com/r/python"><span>reddit</span></a></p>
<p id="hello" class="hello">Oh yes! check out <a href="http://reddit.com/r/python"><span>reddit</span></a></p>
<p id="hello" class="hello">Oh yes! check out <a href="http://reddit.com/r/python"><span>reddit</span></a></p>
<div class="wrap"><div id="test"><p id="hello" class="hello">Oh yes! check out <a href="http://reddit.com/r/python"><span>reddit</span></a></p><a href="http://cuiqingcai.com">Germy</a></div></div>
<div class="wrap"/>

这不需要多解释了吧。

DOM 操作也是与 jQuery 如出一辙。

遍历

遍历用到 items 方法返回对象列表,或者用 lambda

 
1
2
3
4
5
6
7
from pyquery import PyQuery as pq
doc = pq(filename='hello.html')
lis = doc('li')
for li in lis.items():
    print li.html()
 
print lis.each(lambda e: e)

运行结果

 
1
2
3
4
5
6
7
8
9
10
first item
<a href="link2.html">second item</a>
<a href="link3.html"><span class="bold">third item</span></a>
<a href="link4.html">fourth item</a>
<a href="link5.html">fifth item</a>
<li class="item-0">first item</li>
<li class="item-1"><a href="link2.html">second item</a></li>
<li class="item-0 active"><a href="link3.html"><span class="bold">third item</span></a></li>
<li class="item-1 active"><a href="link4.html">fourth item</a></li>
<li class="item-0"><a href="link5.html">fifth item</a></li>

不过最常用的还是 items 方法

网页请求

PyQuery 本身还有网页请求功能,而且会把请求下来的网页代码转为 PyQuery 对象。

 
1
2
3
from pyquery import PyQuery as pq
print pq('http://cuiqingcai.com/', headers={'user-agent': 'pyquery'})
print pq('http://httpbin.org/post', {'foo': 'bar'}, method='post', verify=True)

感受一下,GET,POST,样样通。

Ajax

PyQuery 同样支持 Ajax 操作,带有 get 和 post 方法,不过不常用,一般我们不会用 PyQuery 来做网络请求,仅仅是用来解析。

PyQueryAjax

API

最后少不了的,API大放送。

API

原汁原味最全的API,都在里面了!如果你对 jQuery 语法不熟,强烈建议先学习下 jQuery,再回来看 PyQuery,你会感到异常亲切!

结语

用完了 PyQuery,我已经深深爱上了他!

你呢?

转载:静觅 » Python爬虫利器六之PyQuery的用法

Python爬虫利器六之PyQuery的用法的更多相关文章

  1. Python爬虫利器五之Selenium的用法

    1.简介 Selenium 是什么?一句话,自动化测试工具.它支持各种浏览器,包括 Chrome,Safari,Firefox 等主流界面式浏览器,如果你在这些浏览器里面安装一个 Selenium 的 ...

  2. Python爬虫利器四之PhantomJS的用法

    前言 大家有没有发现之前我们写的爬虫都有一个共性,就是只能爬取单纯的html代码,如果页面是JS渲染的该怎么办呢?如果我们单纯去分析一个个后台的请求,手动去摸索JS渲染的到的一些结果,那简直没天理了. ...

  3. Python爬虫进阶六之多进程的用法

    前言 在上一节中介绍了thread多线程库.python中的多线程其实并不是真正的多线程,并不能做到充分利用多核CPU资源. 如果想要充分利用,在python中大部分情况需要使用多进程,那么这个包就叫 ...

  4. python爬虫(10)--PyQuery的用法

    简介 pyquery 可让你用 jQuery 的语法来对 xml 进行操作.这I和 jQuery 十分类似.如果利用 lxml,pyquery 对 xml 和 html 的处理将更快. 初始化 在这里 ...

  5. Python 爬虫十六式 - 第六式:JQuery的假兄弟-pyquery

    PyQuery:一个类似jquery的python库 学习一时爽,一直学习一直爽   Hello,大家好,我是 Connor,一个从无到有的技术小白.上一次我们说到了 BeautifulSoup 美味 ...

  6. Python爬虫十六式 - 第三式:Requests的用法

    Requests: 让 HTTP 服务人类 学习一时爽,一直学习一直爽   Hello,大家好,我是Connor,一个从无到有的技术小白.今天我们继续来说我们的 Python 爬虫,上一次我们说到了 ...

  7. (转)Python爬虫利器一之Requests库的用法

    官方文档 以下内容大多来自于官方文档,本文进行了一些修改和总结.要了解更多可以参考 官方文档 安装 利用 pip 安装 $ pip install requests 或者利用 easy_install ...

  8. Python爬虫利器二之Beautiful Soup的用法

    上一节我们介绍了正则表达式,它的内容其实还是蛮多的,如果一个正则匹配稍有差池,那可能程序就处在永久的循环之中,而且有的小伙伴们也对写正则表达式的写法用得不熟练,没关系,我们还有一个更强大的工具,叫Be ...

  9. Python爬虫利器一之Requests库的用法

    前言 之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助.入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取.那么这一节来 ...

随机推荐

  1. [BZOJ4802]欧拉函数

    bzoj description 给出\(n\),求\(\varphi(n)\).\(n\le10^{18}\) sol \(Pollard\ Rho\),存个代码. code #include< ...

  2. Archiva与maven配置使用

    在之前的博文里头已经介绍了Archiva私服的使用,本文主要介绍,如何与maven进行配置,在进行maven使用的时候可以自动上传至Archiva上 1.设置maven的用户配置,到maven的安装目 ...

  3. 记录一次MyEclipse工程搭建的辛酸

    一个历史项目,使用的是Myeclipse6.5版本:这一天就砸在这个项目了. 调通web项目:内置的是tomcat插件,貌似和eclipse的server版的还不太一样. 长这个样子:

  4. linux系统报错日志学习

    linux本身会自动记录系统报错日志:/var/log/messages 这个日志记录,我是在什么时候发现其强大的作用的呢?它有点像我们使用php脚本开发接口的时候技术员在重要地方打日志的效果,方便技 ...

  5. Python 迭代对象、迭代器、生成器

    原文出处: liuzhijun 本文源自RQ作者的一篇博文,原文是Iterables vs. Iterators vs. Generators,俺写的这篇文章是按照自己的理解做的参考翻译,算不上是原文 ...

  6. 【详解】Linux的文件描述符fd与文件指针FILE*互相转换

    使用系统调用的时候用文件描述符(file descriptor,简称fd)的时候比较多,但是操作比较原始.C库函数在I/O上提供了一些方便的包装(比如格式化I/O.重定向),但是对细节的控制不够. 如 ...

  7. GIT的安装及上传代码到码云

    前言 昨天初次接触GIT及码云,虽然用了2个多小时才搞定,但是还是挺开心的.码云是一个可以储存我们写的代码的一个平台,而Git是一款免费.开源的分布式版本控制系统,可以敏捷高效地处理任何或小或大的项目 ...

  8. 【并发编程】Future和FutureTask以及CompletionService

    Future接口 此接口主要用于: 代表异步计算的执行结果: 用于可取消的task:(比使用interrupt实现取消要方便 ) FutureTask类 FutureTask是Future的一个实现类 ...

  9. 学习笔记之C++ Primer中文版(第五版)

    非常权威系统的语言书,正好学习下C++11内容. C++ Primer_百度百科 http://baike.baidu.com/link?url=YLvDJE9w3CjGp3eQwjuXYKUZs7v ...

  10. jquery textSearch实现页面搜索 注意!!!!调用这个插件后,js事件绑定如,on、bind、live delegate全部失效,折腾了我一整天!!!

    今天我们介绍的这个插件来着http://www.zhangxinxu.com/wordpress/,张鑫旭的文章写得挺好的,大家有兴趣的多看看. 我们今天的这个插件叫“jquery.textSearc ...