【问题标题】:Access to a specific table in html tag访问 html 标记中的特定表
【发布时间】:2016-06-01 05:29:24
【问题描述】:

我将使用beautifulsoup在以下链接中查找“内容逻辑定义”中定义的表:

1) https://www.hl7.org/fhir/valueset-account-status.html
2) https://www.hl7.org/fhir/valueset-activity-reason.html
3) https://www.hl7.org/fhir/valueset-age-units.html 

可以在页面中定义多个表。我想要的表位于<h2> tag with text “content logical definition” 下。某些页面可能在“内容逻辑定义”部分中缺少任何表,因此我希望该表为空。到目前为止,我尝试了几种解决方案,但每个解决方案都为某些页面返回了错误的表格。

alecxe 提供的最后一个解决方案是:

import requests
from bs4 import BeautifulSoup

urls = [
    'https://www.hl7.org/fhir/valueset-activity-reason.html',
    'https://www.hl7.org/fhir/valueset-age-units.html'
]

for url in urls:
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')

    h2 = soup.find(lambda elm: elm.name == "h2" and "Content Logical Definition" in elm.text)
    table = None
    for sibling in h2.find_next_siblings():
        if sibling.name == "table":
            table = sibling
            break
        if sibling.name == "h2":
            break
    print(table)

如果“内容逻辑定义”部分中没有表,则此解决方案返回 null,但对于“内容逻辑定义”中包含表的第二个 url,它返回错误的表,即页面末尾的表。
如何编辑此代码以访问恰好在具有“内容逻辑定义”文本的标记之后定义的表,如果本节中没有表,则返回 null。

【问题讨论】:

  • 网页中有三个表格。你在找哪张桌子?
  • 您能准确指出是哪个页面给您带来了问题吗?我不清楚您指的是哪个第二个网址。
  • 你愿意使用 lxml 吗?

标签: python html mysql beautifulsoup bs4


【解决方案1】:

看起来 alecxe 的代码的问题在于它返回的表是 h2 的直接兄弟,但您想要的实际上是在一个 div 中(这是 h2 的兄弟)。这对我有用:

import requests
from bs4 import BeautifulSoup

urls = [
    'https://www.hl7.org/fhir/valueset-account-status.html',
    'https://www.hl7.org/fhir/valueset-activity-reason.html',
    'https://www.hl7.org/fhir/valueset-age-units.html'
]


def extract_table(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'lxml')

    h2 = soup.find(lambda elm: elm.name == 'h2' and 'Content Logical Definition' in elm.text)
    div = h2.find_next_sibling('div')
    return div.find('table')


for url in urls:
    print extract_table(url)

【讨论】:

  • @Noah,非常感谢!,这是一个很棒的代码,效果很好。请您在以下链接中检查我的另一个问题:“stackoverflow.com/questions/37555709/…”。再次感谢您!
  • @Padraic,感谢您的评论!那你有什么建议呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-10
  • 2018-01-02
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多