Is it possibile to modify a link value with Beautifulsoup without recreating the all link?
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?
<开发者_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.
精彩评论