2017-08-11 61 views
0

我解析表使用此模式代碼:分析表的列與BeautifulSoup

soup = BeautifulSoup(open("out.html"), 'html.parser') 
tab = soup.findAll('table')[3] 
rows = tab.find_all('tr') 

for sing_row in rows: 
    col = sing_row.find_all('td')[1] 
    print col 

打印的結果是:

<td class="col-md-3">5.67.43.158<br/><span style="font-size: 0.9em; color: #eee;"></span></td> 
<td class="col-md-3">32.54.44.155<br/><span style="font-size: 0.9em; color: #eee;">ns2.asdf.it</span></td> 
<td class="col-md-3">53.64.21.154<br/><span style="font-size: 0.9em; color: #eee;">server1.adb.it</span></td> 
<td class="col-md-3">23.62.53.22<br/><span style="font-size: 0.9em; color: #eee;">server1.xcvf.it</span></td> 

我的目標是從表中只獲取IP地址沒有跨度內的域的列。我該如何繼續?

+0

嘗試'sing_row.find_all( 'TD')[1] .contents' –

+0

馬庫斯如果提供的答案符合您的要求,那麼您應該將其標記爲「已接受」。 –

+0

僅供參考:https://stackoverflow.com/help/someone-answers –

回答

0

可以使用tag.contents

for sing_row in rows: 
    col = sing_row.find_all('td')[1] 
    print col.contents 

也可以使用tag.find(text=True)

for sing_row in rows: 
    col = sing_row.find_all('td')[1] 
    print col.find(text=True) 
+0

非常感謝。 – Marcus

+0

@Marcus你有沒有看到我發佈的鏈接? https://stackoverflow.com/help/someone-answers你可以這樣說謝謝:) –