Velvet Star Monitor

Standout celebrity highlights with iconic style.

news

How to get a especif class after other especific class in python with beautiful soup?

Writer 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

3

1 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.