NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.

theDataDigger發表於2019-02-13
soup=BeautifulSoup(html.text,`lxml`)
#data=soup.select(`body > div.main > div.ctr > div > div.newsmcont > p:nth-of-type(3) > img`)
#data=soup.select(`body > div.main > div.ctr > div > div.newsmcont > p > img`)[2]
data=soup.select(`body > div.main > div.ctr > div > div.newsmcont > p:nth-child(3) > img`)
print(data)

當使用copy selector時,複製的是nth-child,而soup 似乎不支援nth-child,所以會報以下錯誤:

NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.

將nth-child 改為 nth-of-type 就可以了。

或者去掉nth-child,在後面加上[i-1],即[2]。

關於nth-child 和 nth-type,他們都是取父元素下的第n個元素,他們的區別可以通過下面這個例子瞭解一下:

<div> 
<ul class="demo"> 
<p>zero</p> 
<li>one</li> 
<li>two</li> 
</ul> 
</div>

上面這個例子,.demo li:nth-child(2)選擇的是<li>one</li>節點,.demo li:nth-of-type(2)則選擇的是<li>two</li>節點。

相關文章