From : http://cuiqingcai.com/2636.html
前言
你是否觉得 XPath 的用法多少有点晦涩难记呢?
你是否觉得 BeautifulSoup 的语法多少有些悭吝难懂呢?
你是否甚至还在苦苦研究正则表达式却因为少些了一个点而抓狂呢?
你是否已经有了一些前端基础了解选择器却与另外一些奇怪的选择器语法混淆了呢?
嗯,那么,前端大大们的福音来了,PyQuery 来了,乍听名字,你一定联想到了 jQuery,如果你对 jQuery 熟悉,那么 PyQuery 来解析文档就是不二之选!包括我在内!
PyQuery 是 Python 仿照 jQuery 的严格实现。语法与 jQuery 几乎完全相同,所以不用再去费心去记一些奇怪的方法了。
W3School jQuery 教程 PyQuery官方文档安装
pip install pyquery
使用方法简介。更多更全的方法可以直接去看 官方文档。
from pyquery import PyQuery as pq
# 1.可加载一段HTML字符串,或一个HTML文件,或是一个url地址,
d=pq("<html><title>hello</title></html>")
d=pq(filename=path_to_html_file)
d=pq(url='http://www.baidu.com')注意:此处url似乎必须写全
# 2.html()和text() ——获取相应的HTML块或文本块,
p=pq("<head><title>hello</title></head>")
p('head').html()#返回<title>hello</title>
p('head').text()#返回hello
# 3.根据HTML标签来获取元素,
d=pq('<div><p>test 1</p><p>test 2</p></div>')
d('p')#返回[<p>,<p>]
print d('p')#返回<p>test 1</p><p>test 2</p>
print d('p').html()#返回test 1
# 注意:当获取到的元素不只一个时,html()、text()方法只返回首个元素的相应内容块
# 4.eq(index) ——根据给定的索引号得到指定元素。接上例,若想得到第二个p标签内的内容,则可以:
print d('p').eq(1).html() #返回test 2
# 5.filter() ——根据类名、id名得到指定元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('p').filter('#1') #返回[<p#1>]
d('p').filter('.2') #返回[<p.2>]
# 6.find() ——查找嵌套元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('div').find('p')#返回[<p#1>, <p.2>]
d('div').find('p').eq(0)#返回[<p#1>]
#7.直接根据类名、id名获取元素,例:
d=pq("<div><p id='1'>test 1</p><p class='2'>test 2</p></div>")
d('#1').html()#返回test 1
d('.2').html()#返回test 2
# 8.获取属性值,例:
d=pq("<p id='my_id'><a href='http://hello.com'>hello</a></p>")
d('a').attr('href')#返回http://hello.com
d('p').attr('id')#返回my_id
# 9.修改属性值,例:
d('a').attr('href', 'http://baidu.com')把href属性修改为了baidu
# 10.addClass(value) ——为元素添加类,例:
d=pq('<div></div>')
d.addClass('my_class')#返回[<div.my_class>]
# 11.hasClass(name) #返回判断元素是否包含给定的类,例:
d=pq("<div class='my_class'></div>")
d.hasClass('my_class')#返回True
# 12.children(selector=None) ——获取子元素,例:
d=pq("<span><p id='1'>hello</p><p id='2'>world</p></span>")
d.children()#返回[<p#1>, <p#2>]
d.children('#2')#返回[<p#2>]
# 13.parents(selector=None)——获取父元素,例:
d=pq("<span><p id='1'>hello</p><p id='2'>world</p></span>")
d('p').parents()#返回[<span>]
d('#1').parents('span')#返回[<span>]
d('#1').parents('p')#返回[]
# 14.clone() ——返回一个节点的拷贝
#15.empty() ——移除节点内容
# 16.nextAll(selector=None) ——返回后面全部的元素块,例:
d=pq("<p id='1'>hello</p><p id='2'>world</p><img scr='' />")
d('p:first').nextAll()#返回[<p#2>, <img>]
d('p:last').nextAll()#返回[<img>]
# 17.not_(selector) ——返回不匹配选择器的元素,例:
d=pq("<p id='1'>test 1</p><p id='2'>test 2</p>")
d('p').not_('#2')#返回[<p#1>]
快速体验
在这里介绍四种初始化方式。
(1)直接字符串
from pyquery import PyQuery as pq
doc = pq("<html></html>")
pq 参数可以直接传入 HTML 代码,doc 现在就相当于 jQuery 里面的 $ 符号了。
(2)lxml.etree
from lxml import etree
doc = pq(etree.fromstring("<html></html>"))
可以先用 lxml 的 etree 处理一下代码,这样如果你的 HTML 代码出现一些不完整或者疏漏,都会自动转化为完整清晰结构的 HTML代码。
(3)直接传URL
from pyquery import PyQuery as pq
doc = pq('http://www.baidu.com')
这里就像直接请求了一个网页一样,类似用 urllib2 来直接请求这个链接,得到 HTML 代码。
(4)传文件
from pyquery import PyQuery as pq
doc = pq(filename='hello.html')
可以直接传某个路径的文件名。
示例
现在我们以本地文件为例,传入一个名字为 hello.html 的文件,文件内容为
<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>
编写如下程序
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()
运行结果
<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 语法)的对象!
属性操作
可以完全按照 jQuery 的语法来进行 PyQuery 的操作。
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")
运行结果
hello
<p id="plop" class="hello"/>
<p id="hello" class="hello"/>
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'})
运行结果
<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; background-color: yellow"/>
在这里我们发现了,这是一连串的操作,而 p 是一直在原来的结果上变化的。
因此执行上述操作之后,p 本身也发生了变化。
DOM操作
同样是 jQuery 语法
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
运行结果
<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
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)
运行结果
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 对象。
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 来做网络请求,仅仅是用来解析。
API
最后少不了的,API大放送。
最全的API,都在里面了!如果你对 jQuery 语法不熟,强烈建议先学习下 jQuery,再回来看 PyQuery,你会感到异常亲切!