【问题标题】:BeautifulSoup nth-of-type returns empty list. Soup.select()[n -1] returns the elements. Why?BeautifulSoup nth-of-type 返回空列表。 Soup.select()[n -1] 返回元素。为什么?
【发布时间】:2016-06-21 03:49:26
【问题描述】:

我正在尝试抓取this page

我的汤选择器是:

test = soup.select('#bodyContent > #mw-content-text > table.wikitable:nth-of-type(4)')

这应该返回#cmw-content-text 的第四个子表。

但它返回一个空列表。

但如果我查询:

test = soup.select('#bodyContent > #mw-content-text > table.wikitable')[3]

我确实得到了相同的选择器。

我的实现中缺少什么?

【问题讨论】:

  • 也许第四个#mw-content-text > table 不是.wikitable。 :nth-of-type() 不等同于索引器。
  • 是的。否则它不会出现在列表中。

标签: python web-scraping css-selectors beautifulsoup


【解决方案1】:

这是因为您不能将nth-of-type() 与分类标签一起使用,它只能用于type 元素,例如:table:nth-of-type(4)。对于这个特定的实例

test = soup.select('#bodyContent > #mw-content-text > table.wikitable:nth-of-type(4)')

不可能,因此您应该使用您在问题中建议的解决方法

test = soup.select('#bodyContent > #mw-content-text > table.wikitable')[3]

还可以查看this great question and subsequent answer,了解如何在 CSS3 中使用 :nth-of-type()

【讨论】:

    猜你喜欢
    • 2020-02-16
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 2012-11-29
    相关资源
    最近更新 更多