我有:
<h2 id='names'>Names</h2>
<p>John</p>
<p>Peter</p>
Run Code Online (Sandbox Code Playgroud)
如果我已经拥有h2标签,那么现在最简单的方法就是将Peter带到这里?现在我试过了:
soup.select("#names > p:nth-child(1)")
Run Code Online (Sandbox Code Playgroud)
但在这里我得到了nth-child NotImplementedError:
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
Run Code Online (Sandbox Code Playgroud)
所以我不确定这里发生了什么.第二种选择是让所有'p'标记子项和硬选择[1]但是那时存在索引超出范围的危险,这将需要围绕每次尝试以获得彼得的尝试/除了有点愚蠢.
有没有办法用soup.select()函数选择nth-child?
编辑: 用nth-type替换nth-child似乎可以解决问题,所以正确的行是:
soup.select("#names > p:nth-of-type(1)")
Run Code Online (Sandbox Code Playgroud)
不确定为什么它不接受nth-child但似乎nth-child和nth-of-type返回相同的结果.