Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python method chaining in a for loop

I have a list of html tags defined as below:

tags = ["text1", "text2", "text3"]

I will need to use theses values in a method chaining as shown below:

soup.find("div", class_="text1").find("div", class_="text2").find("div", class_="text3").text

Since the list is dynamic, is there any way i can make the method chaining find() dynamic as well (in a for loop maybe?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

def find_chained(soup, classes):
    for cls in classes:
        soup = soup.find("div", class_=cls)
    return soup.text

Should be self-explanatory: loop over each item; the tag you found is now the new "base" tag within which you want to find the next div.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading