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

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

问题描述

我有:

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

现在什么对这里得到的彼得,如果我有H2标签已经是最简单的方法是什么?现在,我已经试过:

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]但有指标超出范围/危险这就需要围绕千方百计获得的彼得的与尝试,除了这是一个有点傻了。

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.

任何方式选择第n个孩子soup.select()函数?

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

编辑:
与第n-的类型似乎这样的伎俩更换第n个孩子,所以正确的路线是:

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)")

不知道为什么它不接受第n个孩子,但似乎双方第n个孩子,第n-的类型返回相同的结果。

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

推荐答案

第n个的孩子根本就没有在beautifulsoup4实施(在撰写本文时),根本就在beautifulsoup $ C无code $ CBase的做到这一点。作者明确添加了NotImplementedError来解释这一点,<一个href=\"http://bazaar.launchpad.net/~leonardr/beautifulsoup/bs4/view/head:/bs4/element.py?start_revid=342#L1261\"相对=nofollow>这里是code

'nth-of-child' is simply not implemented in beautifulsoup4 (at time of writing), there is simply no code in the beautifulsoup codebase to do it. The authors explicitly added the 'NotImplementedError' to explain this, here is the code

给你在你的问题你报价是不是在找H2#名称的孩子的HTML。

Given the html you quote in your question you are not looking for a child of h2#names.

你真正寻找的是第二个相邻的兄弟姐妹,我不是一个CSS选择器大师,但我发现这个工作。

What you are really looking for is the second adjacent sibling, I'm not a css selector guru but I found that this worked.

soup.select("#names + p + p")

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

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