BeautifulSoup nth-of-type返回空列表。 Soup.select()[n -1]返回元素。为什么呢?

时间:2016-03-07 14:34:35

标签: python web-scraping css-selectors beautifulsoup

我正在试图抓this page

我的汤选择器是:

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

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

但它正在返回一个空列表。

但如果我查询:

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

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

我的实施中缺少什么?

1 个答案:

答案 0 :(得分:3)

之所以发生这种情况是因为您无法将nth-of-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]

另请查看有关在CSS3中使用:nth-of-type()的{​​{3}}。