How to get a especif class after other especific class in python with beautiful soup?
Olivia Zamora
In the website source i found this:
<div class = "g">..<\div> <div class = "g">..<\div> <div class = "g">..<\div> <div class = "g">..<\div> <jsmodel="gpo5Gf"...>..<\div> <div class = "g">..<\div> <div class = "g">..<\div>I need to acces/get the information of the class "g", but only those that are after the jsmodel
Can someone help me?
I'm using python3/beautifulsoup
31 Answer
I assumed that you mean <div jsmodel="..." instead of <jsmodel="..."
BeautifulSoup has many functions - not only find() and find_all().
There is also find_next(), find_all_next(), find_next_sibling(), find_next_siblings(), etc.
So you can use find() to div with jsmodel and later use find_next() to search next element.
text = '''
<div>..</div>
<div>..</div>
<div jsmodel="gpo5Gf">..</div>
<div>FIRST</div>
<div>SECOND</div>
<div>OTHER class</div>
'''
from bs4 import BeautifulSoup as BS
soup = BS(text, 'html.parser')
model = soup.find('div', {'jsmodel': True})
#model = soup.find('div', {'jsmodel': "gpo5Gf"})
div = model.find_next('div')
#div = model.find_next('div', {'class', 'g'})
print(div) 2