【问题标题】:Extract specific columns in the row after each bold heading in HTML table use BeautifulSoup在 HTML 表中每个粗体标题后提取行中的特定列使用 BeautifulSoup
【发布时间】:2017-09-22 20:08:56
【问题描述】:

我正在尝试使用 BeautifulSoup 在一个 html 表中的第一个和第二个粗体标题之后的下一行中提取第 1 列和第 3 列中的文本。粗体文本没有类或 ID,并且位于与它们上方和下方的行相同的级别。我想我应该使用 next_sibling,但我不知道该怎么做。

您可以在此处找到表格的 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)

【问题讨论】:

  • 可以分享一下html结构吗?

标签: python html web-scraping beautifulsoup


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2016-06-15
    • 2021-05-31
    • 1970-01-01
    相关资源
    最近更新 更多