用soup.select在美丽的汤中选择第二个孩子? [英] selecting second child in beautiful soup with soup.select?

查看:26
本文介绍了用soup.select在美丽的汤中选择第二个孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

<h2 id='names'>Names</h2>
<p>John</p>
<p>Peter</p>

如果我已经有 h2 标签,那么现在将 Peter 带到这里的最简单方法是什么?现在我试过了:

now what's the easiest way to get the Peter here if I have h2 tag already? Now I've tried:

soup.select("#names > p:nth-child(1)")

但在这里我得到了第 n 个孩子的 NotImplementedError:

but here I get nth-child NotImplementedError:

NotImplementedError: Only the following pseudo-classes are implemented: nth-of-type.

所以我不确定这里发生了什么.第二种选择是只获取所有 'p' 标签子项并硬选择 [1],但是存在索引超出范围的危险,这需要围绕每次尝试使用 try/except 获取 Peter这有点傻.

So I'm not sure what's going on here. The second option was to just get all 'p' tag children and hard select [1] but then there's a danger of index out of range which would require to surround every attempt to get Peter with try/except which is a bit silly.

有没有办法用soup.select()函数选择第n个孩子?

Any way to select nth-child with soup.select() function?

用 nth-of-type 替换 nth-child 似乎可以解决问题,所以正确的行是:

replacing nth-child with nth-of-type seemed to do the trick, so the correct line is:

soup.select("#names > p:nth-of-type(1)")

不知道为什么它不接受 nth-child 但似乎 nth-child 和 nth-of-type 返回相同的结果.

not sure why it doesn't accept nth-child but it seems that both nth-child and nth-of-type return the same results.

推荐答案

将您的编辑添加为答案,以便其他人更容易找到它:

Adding your edit as an answer so that it can be more easily found by others:

使用 nth-of-type 代替 nth-child:

soup.select("#names > p:nth-of-type(1)")

这篇关于用soup.select在美丽的汤中选择第二个孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆