2010-05-25 66 views
2

从HTML输入像这样开始:是否可以通过Beautifulsoup修改链接值而不重新创建所有链接?

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

是有可能修改<a>节点值(“这个我foo”和“这是栏”)添加后缀“经分析”的值而无需重新创建全部链接?
结果必须是这样的:

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

和代码应该是这样的:

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 

回答

3

如果我理解正确的话,那么你就要成功了。 更改您的代码

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

如果我们打印出html_out我们得到:

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

我认为这是你想要的。

+0

link_tag.string = link_tag.string +'_PARSED'不起作用。 – systempuntoout 2010-05-25 17:41:51

+0

@systempuntoout,你确定吗?它对我来说很漂亮。我正在使用版本3.0.8.1。 – 2010-05-25 19:01:15

+0

我正在用DarwinPort下载3.07a。 3.08作品像一个魅力:)谢谢。 – systempuntoout 2010-05-25 19:26:48

相关问题