【问题标题】:How to scrape td corresponding to header text in Beautifulsoup如何在 Beautifulsoup 中刮取与标题文本对应的 td
【发布时间】:2020-08-30 04:20:28
【问题描述】:

我正在尝试使用 Beautiful Soup 抓取维基百科。我想获取里面的文本,但只获取带有特定标题文本的行的内容。

例如: 我想获取 Alan Turing 从https://en.wikipedia.org/wiki/Alan_Turing 获得的奖项列表

我需要的信息在右表中,在表头对应的表数据中,带有文本Awards。如何获得奖项列表?

我尝试遍历表格行并检查表格标题是否等于“Awards”,但我不知道如何停止循环以防表格中没有“Awards”标题。

testurl = "https://en.wikipedia.org/wiki/Alan_Turing"
page = requests.get(testurl)
page_content = BeautifulSoup(page.content, "html.parser")
table = page_content.find('table' ,attrs={'class':'infobox biography vcard'})
while True:
    tr = table.find('tr')
    if tr.find('th').renderContents() == 'Awards':
        td = tr.find('td')
        break
print(td)

【问题讨论】:

  • 你能展示一下你尝试过的东西吗?

标签: python web-scraping beautifulsoup


【解决方案1】:

您可以使用 CSS 选择器 th:contains("Awards") - 这将选择包含文本 Awards<th> 标记。

然后+ td a[title] 将选择下一个兄弟<td> 和每个带有title= 属性的<a> 标签:

import requests
from bs4 import BeautifulSoup


url = 'https://en.wikipedia.org/wiki/Alan_Turing'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

awards = [a.text for a in soup.select('th:contains("Awards") + td a[title]')]
print(awards)

打印:

["Smith's Prize"]

对于url = 'https://en.wikipedia.org/wiki/Albert_Einstein',它将打印:

['Barnard Medal', 'Nobel Prize in Physics', 'Matteucci Medal', 'ForMemRS', 'Copley Medal', 'Gold Medal of the Royal Astronomical Society', 'Max Planck Medal', 'Member of the National Academy of Sciences', 'Time Person of the Century']

2021 年 10 月 31 日更新

beautifulsoup4版本4.10.0

th:contains 现已弃用,请使用 th:-soup-contains 代替 th:contains

示例

awards = [a.text for a in soup.select('th:-soup-contains("Awards") + td a[title]')]

【讨论】:

    【解决方案2】:

    以下是访问“奖励”部分的方法。希望对你有帮助

    from bs4 import BeautifulSoup
    import urllib.request
    
    testurl = "https://en.wikipedia.org/wiki/Alan_Turing"
    page = urllib.request.urlopen(testurl)
    page_content = BeautifulSoup(page, "html.parser")
    table = page_content.find('table' ,attrs={'class':'infobox biography vcard'})
    
    for link in table.find_all('th'):
        if link.text == 'Awards':
            your_needed_variable = link.text
    
    print(your_needed_variable)
    

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 2022-12-29
      • 2020-08-29
      • 2019-08-18
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 2021-10-18
      相关资源
      最近更新 更多