gpt4 book ai didi

html - BeautifulSoup 中的第 n 个类型 NotImplementedError

转载 作者:行者123 更新时间:2023-11-28 01:07:53 27 4
gpt4 key购买 nike

我是 Python 的初学者,我正在尝试实现一个网络爬虫来抓取一些调查数据。我正在尝试使用第 nth-of-type CSS 选择器(因为那是 BeautifulSoup 允许我使用的唯一伪类)来选择父元素的第 7 个元素(即,如果您访问调查,它就是全部的平均分数)。我在下面编写了抛出 NotImplementedError 的代码,即使我已经在 http://jsfiddle.net/3Ycu9/ 中测试了选择器。我只使用 nth-of-type 和一个属性选择器。有人可以帮我弄清楚为什么会出现此错误吗?

import requests, bs4
res = requests.get('http://www.eecs.umich.edu/eecs/undergraduate/survey/all_survey.2016.htm')
res.raise_for_status()
survey = bs4.BeautifulSoup(res.text, "html.parser")
classes = survey.select('td[colspan=3]')

# select the 7th <td> element in every <tr> tag
difficulty = survey.select('td[style*="border-top:none;border-left:none"]:nth-of-type(7)')

for i in range(len(difficulty)):
print(str(difficulty[i].getText()))

最佳答案

nth-of-type 伪类也得到部分支持。它不喜欢您应用的附加属性条件。这一个会经历,例如:

td:nth-of-type(7)

在这里进行直接的 tr->td 关系检查会更有意义:

tr > td:nth-of-type(7)

虽然此页面的标记对于 HTML 解析来说很糟糕。


此处稍微好一点的方法是定位起始行 - 具有 td 元素和 Average Score header 值的行。然后,我们可以通过 tr sibling 收集平均分数,直到“表格”结束:

start_row = survey.find(lambda tag: tag and tag.name == "td" and "Average" in tag.get_text(strip=True)).find_parent("tr")

for row in start_row.find_next_siblings("tr"):
cells = row.find_all("td")

average_score = cells[6].get_text()
print(average_score)

if not average_score:
break

打印:

1.67
1.81
2.51
2.39
2.13
1.67
2.22
2.25
3.08
2.00
1.83

关于html - BeautifulSoup 中的第 n 个类型 NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39007666/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com