【问题标题】:nth-of-type in BeautifulSoup NotImplementedErrorBeautifulSoup NotImplementedError 中的第 n 个类型
【发布时间】:2016-12-24 18:18:24
【问题描述】:

我是 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()))

【问题讨论】:

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


    【解决方案1】:

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

    td:nth-of-type(7)
    

    在这里直接检查tr-&gt;td 关系会更有意义:

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

    这个页面的标记对于 HTML 解析来说很糟糕。


    这里稍微好一点的方法是定位起始行 - 具有 td 元素和 Average Score 标头值的行。然后,我们可以通过tr兄弟姐妹收集平均分,直到“表”结束:

    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
    

    【讨论】:

      猜你喜欢
      • 2012-12-15
      • 2023-03-16
      • 2016-10-23
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2013-06-14
      相关资源
      最近更新 更多