操纵¶
您还可以将内容添加到标记末尾:
>>> d = pq('<p class="hello" id="hello">you know Python rocks</p>')
>>> d('p').append(' check out <a href="http://reddit.com/r/python"><span>reddit</span></a>')
[<p#hello.hello>]
>>> print d
<p class="hello" id="hello">you know Python rocks check out <a href="http://reddit.com/r/python"><span>reddit</span></a></p>
或者从一开始:
>>> p = d('p')
>>> p.prepend('check out <a href="http://reddit.com/r/python">reddit</a>')
[<p#hello.hello>]
>>> p.html()
u'check out <a href="http://reddit.com/r/python">reddit</a>you know ...'
将元素前置或追加到其他元素中::
>>> d = pq('<html><body><div id="test"><a href="http://python.org">python</a> !</div></body></html>')
>>> p.prependTo(d('#test'))
[<p#hello.hello>]
>>> d('#test').html()
u'<p class="hello" ...'
在另一个元素之后插入一个元素::
>>> p.insertAfter(d('#test'))
[<p#hello.hello>]
>>> d('#test').html()
u'<a href="http://python.org">python</a> !'
或之前:
>>> p.insertBefore(d('#test'))
[<p#hello.hello>]
>>> d('body').html()
u'<p class="hello" id="hello">...'
为每个元素做一些事情:
>>> p.each(lambda e: e.addClass('hello2'))
[<p#hello.hello2.hello>]
删除元素:
>>> d = pq('<html><body><p id="id">Yeah!</p><p>python rocks !</p></div></html>')
>>> d.remove('p#id')
[<html>]
>>> d('p#id')
[]
删除所选内容:
>>> d('p').empty()
[<p>]
您可以返回修改后的HTML::
>>> print d
<html><body><p/></body></html>
您可以生成HTML内容:
>>> from pyquery import PyQuery as pq
>>> print pq('<div>Yeah !</div>').addClass('myclass') + pq('<b>cool</b>')
<div class="myclass">Yeah !</div><b>cool</b>