python - 是否可以使用 Beautifulsoup 修改链接值而不重新创建所有链接?

标签 python beautifulsoup

从这样的 Html 输入开始:

<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>节点值(“this i foo”和“this is bar”)将后缀“PARSED”添加到值而不重新创建所有链接?
结果需要是这样的:

<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

最佳答案

如果我理解正确的话,那么你就快到了。 将代码更改为

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>

我想这就是你想要的。

关于python - 是否可以使用 Beautifulsoup 修改链接值而不重新创建所有链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2904542/

相关文章:

python - 在 Python 3 包和脚本中导入的最佳实践

python - Django 模型线程安全吗?

通过函数的 Python 对象

Python BS4 抓取 : AttributeError: 'NavigableString' object has no attribute 'text'

python - 类型错误,如果 link.has_attr ('href' ) : TypeError: 'NoneType' object is not callable

python - 从文件读取参数到C和Python脚本

Python imap 库

python - 如何将抓取的数据保存到 CSV 文件中?

python - beautifulsoup 不返回所有 html

python - 使用 beutifulsoup 和 Mechanize 从 html 表中获取文本时出错