2017-11-18 2 views
1

Lange Rede, kurzer Sinn, ich versuche Beautiful Soup zu verwenden, um b Tags durch starke Tags zu ersetzen. Suppe nimmt eine Eingabe, dieSchöne Suppe find_all wrappt zusammen statt einzeln

<b>Words:</b> attributes 
<b>Other Words:</b> other attributes 

ich habe folgende python3 Code enthält:

strong_tag = soup.new_tag("strong") 
if(soup.find('b')): 
    for b_tag in soup.find_all('b'): 
     b_tag.wrap(strong_tag) 

Diese gibt

attributes 
<strong><b>Words:</b><b>Other Words:</b></strong> other attributes 

statt

<strong><b>Words:</b></strong> attributes 
<strong><b>Other Words:</b></strong> other attributes 

Wie kann ich repariere das?

Ich gehe davon aus, dass sobald ich das beheben kann, ich extrahiere() den Inhalt von den b-Tags, nur die starken Tags zurücklassen.

Antwort

1

Sie brauchen nur:

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) 

diese gedruckt werden:

<strong><b>Words:</b></strong> attributes 
<strong><b>Other Words:</b></strong> other attributes 
0

einfach eine Hoffnung Sie es möchten

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

Wie wäre es 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>") 

Ausgang:

<html><body><strong>Words:</strong> attributes 
<strong>Other Words:</strong> other attributes 
</body></html>