2017-09-22 14 views
1

我試圖在使用BeautifulSoup的一個HTML表格中的第一個和第二個粗體標題之後的下一行中提取第1列和第3列中的文本。粗體文本沒有類或標識符,與上面和下面的行處於同一級別。我想我應該使用next_sibling,但我不確定究竟該如何去做。在HTML表格中的每個粗體標題之後抽取行中的特定列使用BeautifulSoup

您可以找到表這裏的HTML:https://github.com/Tokaalmighty/topmover_table_html/blob/master/html

這裏是我的邏輯:

soup=bs(f1,'html.parser') 
topmovers=soup.find('table',{'class':'topmovers'}) 

bold=topmovers.find_all('b') 
gainer=bold[0] 
gainer_name=bold.find('tr').next_sibling 
gcol1=gainer_name[0] 
gcol3=gainer_name[2] 

loser=bold[1] 
loser_name=bold.find('tr').next_sibling 
lcol1=loser_name[0] 
lcol3=loser_name[2] 

print(gcol1,gcol3,lcol1,lcol3) 
+0

你能分享html結構嗎? – eLRuLL

回答

1

你可以使用find_next選擇下一個 'TR',然後用得到的文本stripped_strings

soup=bs(f1,'html.parser') 
topmovers=soup.find('table',{'class':'topmovers'}) 

bold=topmovers.find_all('b') 
gainer=bold[0] 
gainer_name=gainer.find_next('tr') 
gainer_strings = list(gainer_name.stripped_strings) 
gcol1=gainer_strings[0] 
gcol3=gainer_strings[2] 

loser=bold[1] 
loser_name=loser.find_next('tr') 
loser_strings = list(loser_name.stripped_strings) 
lcol1=loser_strings[0] 
lcol3=loser_strings[2] 

print(gcol1, gcol3, lcol1, lcol3) 

麥克德莫特國際6.55比爾巴雷特公司2.87

相關問題