I have:
Names
John
Peter
now what\'s the easiest way to get the Pet
Beautiful Soup 4.7.0 (released at the beginning of 2019) now supports most selectors, including :nth-child:
As of version 4.7.0, Beautiful Soup supports most CSS4 selectors via the SoupSieve project. If you installed Beautiful Soup through
pip, SoupSieve was installed at the same time, so you don’t have to do anything extra.
So, if you upgrade your version:
pip install bs4 -U
You'll be able to use nearly all selectors you'd ever need to, including nth-child.
That said, note that in your input HTML, the #names h2 tag does not actually have any children:
Names
John
Peter
Here, there are just 3 elements, which are all siblings, so
#names > p:nth-child(1)
wouldn't work, even in CSS or Javascript.
If the #names element had the s as children, your selector would work, to an extent:
html = '''
John
Peter
'''
soup = BeautifulSoup(html, 'html.parser')
soup.select("#names > p:nth-child(1)")
Output:
[John
]
Of course, the John is the first child of the #names parent. If you want Peter, use :nth-child(2).
If the elements are all adjacent siblings, you can use + to select the next sibling:
html = '''
Names
John
Peter
'''
soup = BeautifulSoup(html, 'html.parser')
soup.select("#names + p + p")
Output:
[Peter
]