2016-03-07 211 views
0

我试图刮this pageBeautifulSoup类型返回空列表。 Soup.select()[n-1]返回元素。为什么?

我的汤选择是:

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

这应返回#CMW-内容文本的第4子表。

但它返回一个空的列表。

但是,如果我查询:

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

我得到了相同的选择。

我在执行中丢失了什么?

+0

也许第四个'#mw-content-text>表格不是'.wikitable'。 :nth-​​of-type()不等于一个索引器。 – BoltClock

+0

它是。否则它将不在列表中。 –

回答

1

发生这种情况是因为您不能将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()