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

BeautifulSoup: get data in class that change name

I’m using BeautifulSoup to scrape an html page where the information I need are stored in a code like this:

<a class=" l00_PR_lTitleonContext" href="site0.html"> Title 0 </a>
<a class=" l01_PR_lTitleonContext" href="site1.html"> Title 1 </a>
<a class=" l02_PR_lTitleonContext" href="site2.html"> Title 2 </a>
[...]

I’d like to get "Title 0", "Title 1" and "Title 2" but the class name change for each item, so I’m using regex like this:

titles = soup.findAll("a", attrs={"class": re.compile('^TitleonContext.*')})


for title in titles:
   print(title)

But it’s not working (nothing is printed). What am I doing wrong?

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 :

Try using the following regex instead re.compile(r'.*TitleonContext') or re.compile('.*TitleonContext'), otherwise you’re looking for this value to be started with (^).

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