python

偶尔的机会,知道这么个扩展,手贱翻了下文档,发现似乎挺有意思,遂记录一二。

what:

这是一个python版本的jquery,而且是后端执行的,至少官方是这么说的:

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.

what for: 

可以用来:

1) 设定主题

2) html分析

why:

 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.

How:

首先,作者假定网页是utf-8编码的。(如果不是请自行处理)

网页不是utf-8的,请添加以下处理逻辑:

import urllib2
from pyquery import PyQuery as pq

url_instance = urllib2.urlopen('http://your_site')
page_text_raw = url_instance.read()
page_text_unicode = unicode(page_text_raw,'utf-8')
page_dom = pq(page_text_unicode)

  

然后,就可以向jquery一样调用(不是100%,作者都说as much as possible the similar to the JQuery ...)。

api如下:

主要请参考这里

PyQuery.val(value=<NoDefault>)

设置DOM元素的value属性

PyQuery.wrap(value)

这个比较有用,可以同一为一组元素设定父容器,从而改变主题(Theme),demo如下:

d = pq('<div><span>Hey</span><span>you !</span></div>')
print d('span').wrap('<div></div>')

输出:

<div><span>Hey</span></div><div><span>you !</span></div>

备注,还有一个warpAll, 作用是将所有元素统一包在一起,

print d('span').wrapAll('<div></div>')

结果:

<div><span>Hey</span><span>you !</span></div>

PyQuery.toggleClass(value)

这个跟jquery的toggle类似。

html/text/val, 读取/设置html,text,value

 

其他略

原文地址:https://www.cnblogs.com/Tommy-Yu/p/3984703.html