2017-11-18 228 views
1

长话短说,我试图用美丽的汤用强烈的标签取代b标签。 汤需要一些投入,包括美丽的汤find_all包装在一起,而不是单独的

<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标签中提取()内容,只留下强标签。

回答

1

你只需要:

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 
0

简单的一个希望你会喜欢它

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 
0

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