Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Multiple Conditions in BeautifulSoup

We use this code find tags containing the text "Fiscal"

soup.find(class_="label",text=re.compile("Fiscal"))

How do I put multiple conditions in here.

Lets say tags containing "Fiscal" and "year" both.

Or tags containing "Fiscal" and NOT "year"

like image 749
Md. Mohsin Avatar asked Sep 18 '14 08:09

Md. Mohsin


People also ask

How do I select multiple tags in BeautifulSoup?

To find multiple tags, you can use the , CSS selector, where you can specify multiple tags separated by a comma , . To use a CSS selector, use the . select_one() method instead of . find() , or .

How do I search for two classes in beautiful soup?

To find elements by class in Beautiful Soup use the find_all(~) or select(~) method.

How do you get elements in BeautifulSoup?

Using CSS selectors to locate elements in BeautifulSoupUse select() method to find multiple elements and select_one() to find a single element.


1 Answers

If you see that the criteria vary and they might get more complex then you could use a function as a filter e.g.:

Lets say tags containing "Fiscal" and "year" both.

t = soup.find(class_="label", text=lambda s: "Fiscal" in s and "year" in s)

Or tags containing "Fiscal" and NOT "year"

t = soup.find(class_="label", text=lambda s: "Fiscal" in s and "year" not in s)

You could also use a regex here but it might be less readable.

like image 141
jfs Avatar answered Oct 21 '22 21:10

jfs