BeautifulSoup NotImplementedError中的nth-of-type

时间:2016-08-17 23:19:11

标签: html python-3.x web-scraping css-selectors beautifulsoup

我是Python的初学者,我正在尝试实施一个webscraper来抓取一些调查数据。我正在尝试使用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()))

1 个答案:

答案 0 :(得分:1)

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

td:nth-of-type(7)

在此处进行直接tr->td关系检查会更有意义:

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

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

这里稍微好一点的方法是找到起始行 - 具有td元素和Average Score标题值的行。然后,我们可以通过tr兄弟姐妹收集平均分数,直到&#34;表格结束&#34;:

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