我正在尝试抓取 this page
我的 Soup 选择器是:
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]
我得到了相同的选择器。
我在实现中缺少什么?
请您参考如下方法:
发生这种情况是因为您不能将 nth-of-type() 与分类标签一起使用,它只能用于像这样的 type 元素:表: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()。
