开发者

Is it possibile to modify a link value with Beautifulsoup without recreating the all link?

开发者 https://www.devze.com 2023-01-01 10:53 出处:网络
Starting from an Html input like this: <p> <a href=\"http://www.foo.com\" rel=\"nofollow\">this is foo</a>

Starting from an Html input like this:

<p>
<a href="http://www.foo.com" rel="nofollow">this is foo</a>
<a href="http://www.bar.com" rel="nofollow">this is bar</a>
</p>

is it possible to modify the <a> node values ("this i foo" and "this is bar") adding the suffix "PARSED" to the value without recreating the all link?

The result need to be like this:

<开发者_JAVA百科;p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>

And code should be something like:

from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(html)
for link_tag in soup.findAll('a'):
    link_tag.string = link_tag.string + '_PARSED' #This obviously does not work


If I understand you correctly then you're nearly there. Change your code to

for link_tag in soup.findAll('a'):
    link_tag.string = link_tag.string + '_PARSED'
html_out = soup.renderContents()

If we print out html_out we get:

>>> print html_out
<p>
<a href="http://www.foo.com" rel="nofollow">this is foo_PARSED</a>
<a href="http://www.bar.com" rel="nofollow">this is bar_PARSED</a>
</p>

which I think is what you wanted.

0

精彩评论

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