是否可以在不重新创建所有链接的情况下使用Beautifulsoup修改链接值?

2024-04-26 01:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

从如下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”,而不重新创建all链接?
结果应该是这样的:

^{pr2}$

代码应该是:

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

Tags: comhttpfooistagwwwlinkbar
1条回答
网友
1楼 · 发布于 2024-04-26 01:39:28

如果我没听错,那你就快到了。 将代码更改为

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

如果我们打印出html,我们得到:

^{pr2}$

我想这正是你想要的。在

相关问题 更多 >

    热门问题