【发布时间】: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