2

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 need change img element's src attribute, and get the modified html.

any ideas?or any other method?

thanks

alwx
  • 179
  • 2
  • 9

2 Answers2

2

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>'
Community
  • 1
  • 1
Greg Haskins
  • 6,714
  • 2
  • 27
  • 22
  • yes ,but selector(img) return a img list, i want to get the modified full html.thanks – alwx Apr 01 '11 at 19:48
  • I added a code snippet. To get the wrapping HTML back out, use the [`outerHtml()`](http://packages.python.org/pyquery/api.html#pyquery.pyquery.PyQuery.outerHtml) method. – Greg Haskins Apr 01 '11 at 20:23
0

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'}
samplebias
  • 37,113
  • 6
  • 107
  • 103