Gra*_*rus 13 python beautifulsoup web-scraping
我有:
<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返回相同的结果.
Stu*_*ner 13
将您的编辑添加为答案,以便其他人更容易找到它:
使用nth-of-type而不是nth-child:
soup.select("#names > p:nth-of-type(1)")
Run Code Online (Sandbox Code Playgroud)
'nth-of-child'根本没有在beautifulsoup4中实现(在撰写本文时),beautifulsoup代码库中根本没有代码可以执行它.作者明确地添加了'NotImplementedError'来解释这个,这里是代码
鉴于你在问题中引用的html,你不是在寻找一个h2#名字的孩子.
你真正想要的是第二个相邻的兄弟,我不是一个css选择大师,但我发现这很有效.
soup.select("#names + p + p")
Run Code Online (Sandbox Code Playgroud)