Search code examples
pythonpyquery

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

any ideas?or any other method?

thanks


Solution

  • 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>'