【发布时间】:2014-09-03 10:04:22
【问题描述】:
我有:
<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() 函数选择nth-child?
编辑: 用 nth-of-type 替换 nth-child 似乎可以解决问题,所以正确的行是:
soup.select("#names > p:nth-of-type(1)")
不确定为什么它不接受 nth-child,但似乎 nth-child 和 nth-of-type 都返回相同的结果。
【问题讨论】:
标签: python web-scraping beautifulsoup