2016-05-12 74 views
1

有沒有一種很好的方法(例如BeautifulSoup)來簡化HTML表格。我使用的請求,以獲得表,並提取與BeautifulSoup表中,但我需要的表走的:Python簡化HTML表格

<table> 
    <thead></thead> 
    <tbody> 
     <tr> 
      <td><a id="bar">Some text<br></br><span class="foobar">foo </span><small class="foo">bar!</small></a></td> 
     </tr> 
    </tbody> 
</table> 

到:

<table> 
    <thead></thead> 
    <tbody> 
     <tr> 
      <td>Some text\nfoo bar!</td> 
     </tr> 
    </tbody> 
</table> 

通過一個簡單的方法,那麼我想不必去每個標籤和使用soup.get_text()

+0

爲什麼要'

'產量只有一個'\ N'? – Xufox

+0

它應該是

,對不起。我知道它可能是
。但這些是我正在使用的數據。 –

回答

1

您可以替換換行符的BR:它給你

h = """<table> 
    <thead></thead> 
     <tr> 
      <td><a id="bar">Some text<br><br/><span class="foobar">foo </span><small class="foo">bar!</small></a></td> 
     </tr> 
</table>""" 


from bs4 import BeautifulSoup 

soup = BeautifulSoup(h) 

td = soup.select_one("#bar") 
td.br.replace_with("\n") 

td.replace_with(td.text) 


print(repr(soup)) 

<html><body><table>\n<thead></thead>\n<tr>\n<td>Some text\nfoo bar!</td>\n</tr>\n</table></body></html> 
+0

@RadLexus,我不太確定,關鍵是要改變表格? –

+1

對不起 - OP的目標只是讓文本不被標籤打破。我認爲剩餘的HTML仍然會被使用,但似乎並不重要。 – usr2564301

+0

@ RadLexus,別擔心,我想也許我錯過了一些東西。 –