Choosing a second child in a beautiful soup with soup. Choose?

I have:

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

Now, what is the easiest way to get Peter here if I already have an h2 tag? Now I 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 is going on here. The second option was just to get all the ā€œpā€ tags and a hard choice [1], but then there is a risk that the index will be out of range that would require every attempt to get Peter surrounded by try / except, but it's a little silly .

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

EDIT: replacing nth-child with nth-of-type seems to have done 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.

+6
source share
2 answers

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

Given the html you are quoting in your question, you are not looking for a child from h2 # names.

What you're really looking for is a second neighbor brother, I am not a CSS selector guru, but I found that it worked.

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

Adding your edit as an answer so that it is easier to find for others:

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

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

Source: https://habr.com/ru/post/972138/


All Articles