前言

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

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

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

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

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

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

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

安装

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

​pip install pyquery

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

简介

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)直接字符串

​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 语法)的对象!

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

属性操作

你可以完全按照 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,样样通。

 

芝麻HTTP: Python爬虫利器之PyQuery的用法的更多相关文章

  1. 芝麻HTTP: Python爬虫利器之Requests库的用法

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

  2. 芝麻HTTP:Python爬虫利器之Xpath语法与lxml库的用法

    安装 ​pip install lxml 利用 pip 安装即可 XPath语法 XPath 是一门在 XML 文档中查找信息的语言.XPath 可用来在 XML 文档中对元素和属性进行遍历.XPat ...

  3. Python爬虫利器之Beautiful Soup,Requests,正则的用法(转)

    https://cuiqingcai.com/1319.html https://cuiqingcai.com/2556.html https://cuiqingcai.com/977.html

  4. Python爬虫Urllib库的高级用法

    Python爬虫Urllib库的高级用法 设置Headers 有些网站不会同意程序直接用上面的方式进行访问,如果识别有问题,那么站点根本不会响应,所以为了完全模拟浏览器的工作,我们需要设置一些Head ...

  5. Python的爬虫利器之urllib

    urllib包 urllib是一个包含几个模块来处理请求的库:  - urllib.request发送http请求  - urllib.error处理请求过程中出现的异常  - urllib.pars ...

  6. 【Python爬虫】安装 pyQuery 遇到的坑 Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?

    windows 64位操作系统下,用 Python 抓取网页,并用 pyQuery 解析网页 pyQuery是jQuery在python中的实现,能够以jQuery的语法来操作解析HTML文档,十分方 ...

  7. Python爬虫常用之PyQuery

    PyQuery是解析页面常用的库.是python对jquery的封装.下面是一份解析基本页面的代码.后期用到复杂或者实用的方式再增加. from pyquery import PyQuery as p ...

  8. 芝麻HTTP:Python爬虫实战之爬取百度贴吧帖子

    本篇目标 1.对百度贴吧的任意帖子进行抓取 2.指定是否只抓取楼主发帖内容 3.将抓取到的内容分析并保存到文件 1.URL格式的确定 首先,我们先观察一下百度贴吧的任意一个帖子. 比如:http:// ...

  9. 芝麻HTTP:Python爬虫入门之URLError异常处理

    1.URLError 首先解释下URLError可能产生的原因: 网络无连接,即本机无法上网 连接不到特定的服务器 服务器不存在 在代码中,我们需要用try-except语句来包围并捕获相应的异常.下 ...

随机推荐

  1. ant基础[转]

    原文链接:http://www.cnblogs.com/wufengxyz/archive/2011/11/24/2261797.html 1,什么是antant是构建工具2,什么是构建概念到处可查到 ...

  2. 洛谷 [P2701] 巨大的牛棚

    首先,本题是一道最大子矩阵问题,且m,n较小,可以使用DP做, 与 洛谷 [P1387]最大正方形 做法相同. #include <iostream> #include <cstdi ...

  3. BZOJ 3262: 陌上花开 [CDQ分治 三维偏序]

    Description 有n朵花,每朵花有三个属性:花形(s).颜色(c).气味(m),又三个整数表示.现要对每朵花评级,一朵花的级别是它拥有的美丽能超过的花的数量.定义一朵花A比另一朵花B要美丽,当 ...

  4. [Android] Toast问题深度剖析(二)

    欢迎大家前往云+社区,获取更多腾讯海量技术实践干货哦~ 作者: QQ音乐技术团队 题记 Toast 作为 Android 系统中最常用的类之一,由于其方便的api设计和简洁的交互体验,被我们所广泛采用 ...

  5. AGC017 F - Zigzag

    传送门 Time limit : 4sec / Memory limit : 256MB Score : 1600 points Problem Statement There are N(N+1)⁄ ...

  6. CocosCreator游戏开发---菜鸟学习之路(二)SocketIO简易教程

    请先参考教程司令部-SocketIO教程进行相关操作 开发完成后部分用户会出现持续输出 a userConnected的BUG 如下图所示 经过一段时间的BUG检查终于发现了问题所在.每个人碰到的情况 ...

  7. C++11 标准库也有坑(time-chrono)

    恰巧今天调试程序遇到时间戳问题, 于是又搜了搜关于取时间戳,以及时间戳转字符串的问题, 因为 time()   只能取到秒(win和linux) 想试试看能不能找到 至少可以取到毫秒的, 于是, 就找 ...

  8. According to TLD or attribute directive in tag file, attribute value does not accept any expressions报错解决办法

    1.出现原因: 导入的uri由于不是正确的导致这个jstl不支持el的表达式 jstl uri导入错误:   <%@ taglib prefix="c" uri=" ...

  9. 沉淀,再出发——安装windows10和ubuntu kylin15.04双系统心得体会

    安装windows10和ubuntu kylin15.04双系统心得体会 一.安装次序      很简单,两种安装次序,"先安装windows后安装linux:先安装linux后安装wind ...

  10. Flask從入門到入土(三)——Web表單

    Flask-WTF擴展可以把處理Web表單的過程變成一種愉悅的體驗.這個擴展對獨立的WTForms包進行了包裝,方便集成到Flask程序中. Flask-WTF及其依賴可使用pip安裝: pip in ...