2017-11-18 134 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>