开发者

how to use pyquery to modify a node attribute in python

iwant use pyquery to do this.

for example:

html='<div>arya stark<img src="1111"/>ahahah<img src="2222"/></div>'
a=PyQuery(html)

i want to modify the html to

<div>arya stark<img src="aaaa"/>ahahah<img src="bbbb"/></div>

in other words, just nee开发者_JAVA技巧d change img element's src attribute, and get the modified html.

any ideas?or any other method?

thanks


Since PyQuery is meant you mirror jQuery, perhaps this question would be relevant. Long story short, use the attr() method:

>>> html='<div>arya stark<img src="1111"/>ahahah<img src="2222"/></div>'
>>> a=PyQuery(html)
>>> a.outerHtml()
'<div>arya stark<img src="1111">ahahah<img src="2222"></div>'
>>> for img in a('img'):
...     PyQuery(img).attr('src', "whatever")
...
[<img>]
[<img>]
>>> a.outerHtml()
'<div>arya stark<img src="whatever">ahahah<img src="whatever"></div>'


Something like this:

import pyquery

html = '<div>arya stark<img src="1111"/>ahahah<img src="2222"/></div>'
tree = pyquery.PyQuery(html)
tree('img:first').attr('src', 'cccc')
print str(tree)

<div>arya stark<img src="cccc"/>ahahah<img src="2222"/></div>

To apply a function to a selection you can use .each(), but note that bare elements are passed to the function:

>>> from __future__ import print_function
>>> tree('img').each(lambda i, n: print(n.attrib))
{'src': 'cccc'}
{'src': '2222'}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜