我有:
<h2 id='names'>Names</h2>
<p>John</p>
<p>Peter</p>
如果我已经有了 h2 标签,现在让 Peter 最简单的方法是什么?现在我试过了:
soup.select("#names > p:nth-child(1)")
但在这里我得到第 nth-child NotImplementedError:
NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.
所以我不确定这里发生了什么。第二种选择是只获取所有 'p' 标签子项并硬选择 [1],但是存在索引超出范围的危险,这将需要用 try/except 包围每次获取 Peter 的尝试这有点傻。
有什么方法可以用 soup.select() 函数选择第 n 个 child ?
编辑: 用 nth-of-type 替换 nth-child 似乎可以解决问题,所以正确的行是:
soup.select("#names > p:nth-of-type(1)")
不确定为什么它不接受第 nth-child,但似乎 nth-child 和 nth-of-type 都返回相同的结果。
最佳答案
将您的编辑添加为答案,以便其他人可以更轻松地找到它:
使用nth-of-type
代替nth-child
:
soup.select("#names > p:nth-of-type(1)")
关于python - 用soup.select在美汤中选二胎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24720442/