Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

python - selecting second child in beautiful soup with soup.select?

I have:

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

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

but here I get nth-child NotImplementedError:

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

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.

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Use nth-of-type instead of nth-child:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...