2017-09-22 64 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

相关问题