Beautiful Soup find_all 包裹在一起而不是单独包裹
Beautiful Soup find_all wraps together instead of individually
长话短说,我正在尝试使用 Beautiful Soup 将 b 标签替换为强标签。
汤需要一些输入,包括
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
我有以下 python3 代码:
strong_tag = soup.new_tag("strong")
if(soup.find('b')):
for b_tag in soup.find_all('b'):
b_tag.wrap(strong_tag)
这输出
attributes
<strong><b>Words:</b><b>Other Words:</b></strong> other attributes
而不是
<strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
我该如何解决这个问题?
我假设一旦我能解决这个问题,我就可以从 b 标签中提取 () 内容,只留下强标签。
您只需要:
from bs4 import BeautifulSoup
div_test="""
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
"""
soup = BeautifulSoup(div_test,'html.parser')
for b_tag in soup.find_all('b'):
b_tag.wrap(soup.new_tag("strong"))
print(soup)
这将打印:
<strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
简单的一个希望大家喜欢
from BeautifulSoup import BeautifulSoup, Tag
mes=""" <b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(mes)
for a in soup.findAll('b'):
p = Tag(soup, 'strong')
a.replaceWith(p)
p.insert(0, a)
print soup
replace
怎么样?
from bs4 import BeautifulSoup
div_test="""<b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(div_test,'lxml')
str(soup).replace("b>","strong>")
输出:
<html><body><strong>Words:</strong> attributes
<strong>Other Words:</strong> other attributes
</body></html>
长话短说,我正在尝试使用 Beautiful Soup 将 b 标签替换为强标签。 汤需要一些输入,包括
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
我有以下 python3 代码:
strong_tag = soup.new_tag("strong")
if(soup.find('b')):
for b_tag in soup.find_all('b'):
b_tag.wrap(strong_tag)
这输出
attributes
<strong><b>Words:</b><b>Other Words:</b></strong> other attributes
而不是
<strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
我该如何解决这个问题?
我假设一旦我能解决这个问题,我就可以从 b 标签中提取 () 内容,只留下强标签。
您只需要:
from bs4 import BeautifulSoup
div_test="""
<b>Words:</b> attributes
<b>Other Words:</b> other attributes
"""
soup = BeautifulSoup(div_test,'html.parser')
for b_tag in soup.find_all('b'):
b_tag.wrap(soup.new_tag("strong"))
print(soup)
这将打印:
<strong><b>Words:</b></strong> attributes
<strong><b>Other Words:</b></strong> other attributes
简单的一个希望大家喜欢
from BeautifulSoup import BeautifulSoup, Tag
mes=""" <b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(mes)
for a in soup.findAll('b'):
p = Tag(soup, 'strong')
a.replaceWith(p)
p.insert(0, a)
print soup
replace
怎么样?
from bs4 import BeautifulSoup
div_test="""<b>Words:</b> attributes
<b>Other Words:</b> other attributes"""
soup = BeautifulSoup(div_test,'lxml')
str(soup).replace("b>","strong>")
输出:
<html><body><strong>Words:</strong> attributes
<strong>Other Words:</strong> other attributes
</body></html>