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

问题描述 投票:0回答:1

我正试图刮掉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]

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

我的实施中缺少什么?

python web-scraping css-selectors beautifulsoup
1个回答
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]

另请查看this great question and subsequent answer关于在CSS3中使用:nth-of-type()的信息。

© www.soinside.com 2019 - 2024. All rights reserved.