python - 用soup.select在美汤中选二胎?

标签 python web-scraping beautifulsoup

我有:

<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/

相关文章:

mysql - 如何平衡网页抓取的负载

python - BeautifulSoup : get contents of search result tag

python - 如何在Python中重写这个嵌套的for循环?

python - 将 Python 输出导出到 CSV 或文本文件(初学者)

python - 计算div标签的平均高度和平均宽度

python - 一种快速计算非空区域的方法

javascript - 从 YouTube URL 检索 JSON

javascript - 使用 PhantomJS 获取由 Javascript 呈现的 html

python - BeautifulSoup4循环找不到后续元素

python - 属性错误: 'NoneType' object has no attribute 'findNext' >> when retrieving tweets