python beautifulsoup:用字符串中的url替换链接

cal*_*iph 1 python beautifulsoup

在包含 HTML 的字符串中,我有几个想要用纯 href 值替换的链接:

from bs4 import BeautifulSoup
a = "<a href='www.google.com'>foo</a> some text <a href='www.bing.com'>bar</a> some <br> text'
soup = BeautifulSoup(html, "html.parser")

tags = soup.find_all()
for tag in tags:
  if tag.has_attr('href'):
    html = html.replace(str(tag), tag['href'])
Run Code Online (Sandbox Code Playgroud)

不幸的是,这会产生一些问题:

  • html 中的标签使用单引号',但 beautifulsoup 将使用带引号 ( )str(tag)的标签创建。所以不会找到匹配的。"<a href="www.google.com">foo</a>replace()
  • <br>被识别为<br/>. 再次replace()找不到匹配项。

所以看来使用python的replace()方法不会给出可靠的结果。

有没有办法使用 beautifulsoup 的方法用字符串替换标签?

编辑:

str(tag) 的附加值 =<a href="www.google.com">foo</a>

bur*_*ran 5

文档的相关部分:修改树

html="""
<html><head></head>
<body>
<a href="www.google.com">foo</a> some text 
<a href="www.bing.com">bar</a> some <br> text
</body></html>"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'html.parser')
for a_tag in soup.find_all('a'):
    a_tag.string = a_tag.get('href')
print(soup)
Run Code Online (Sandbox Code Playgroud)

输出

<html><head></head>
<body>
<a href="www.google.com">www.google.com</a> some text 
<a href="www.bing.com">www.bing.com</a> some <br/> text
</body></html>
Run Code Online (Sandbox Code Playgroud)