2017-07-29 31 views
0

代替我有一個HTML像這樣:查找並Beautifulsoup

<hmtl> 
    <body> 
     <h1>heading 1</h1> 
     <p>blah</p> 
     <h2>heading 2</h2> 
     <p>blah</p> 
     <h2>heading 3</h2> 
     <p>blah</p> 
    </body> 
</html> 

我希望能夠回到美化文本和HTML不是。

我以爲做到這一點的唯一方法是找到並用標題替換每個標題,再加上一個換行符。

有沒有更好的方法?

+0

你試過'soup.prettify()',這就是它的作用。 – davedwards

回答

0

你可能每頭之後插入一個<br/>標籤,增加標題和內容之間的空間,如果這是你需要什麼:

from bs4 import BeautifulSoup 
soup = BeautifulSoup("""<hmtl> 
    <body> 
     <h1>heading 1</h1> 
     <p>blah</p> 
     <h2>heading 2</h2> 
     <p>blah</p> 
     <h2>heading 3</h2> 
     <p>blah</p> 
    </body> 
</html>""", "html.parser") 

from IPython.display import display, HTML 
chart = HTML(str(soup)) 
display(chart) 

import re 
for header in soup.find_all(name=re.compile(r'^h\d')): 
    br=soup.new_tag('br') 
    header.insert_after(br) 

插入前enter image description here

插入<br/>標籤:

for header in soup.find_all(name=re.compile(r'^h\d')): 
    br=soup.new_tag('br') 
    header.insert_after(br) 

chart = HTML(str(soup)) 
display(chart) 

enter image description here