Using multiple conditions in BeautifulSoup

We use these code search tags containing the text "Fiscal"

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

      

How to place multiple conditions here.

Let's use tags containing "Fiscal" and "year".

Or tags containing "Fiscal" and NOT "year"

+3


source to share


2 answers


If you see that the criteria are different and they can get more complex, you can use the function as a filter, for example:

Let's use tags containing "Fiscal" and "year".

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 can also use regex here, but it might be less readable.

+6


source


You can pass the text as a list (this site is an example from my previous answer :))

import requests
from bs4 import BeautifulSoup

res = requests.get('http://www.snapdeal.com/products/computers-laptops?sort=plrty&')
soup = BeautifulSoup(res.text)

elements = soup.find_all('div', {'class': 'lfloat'}, text=re.compile(r'(14|4)')) # | means 'or'

print elements 

      

prints [<div class="lfloat">(14)</div>, <div class="lfloat">(4)</div>, <div class="lfloat">(45)</div>]



So you can use: soup.find_all(class_="label",text=re.compile(r'(Fiscal|yeah)))

in your case

To find an exact match, you can pass text

as a list:soup.find_all(class_="label",text=['Fiscal', 'yeah'])

The "find fiscal and NOT yes" logics can be covered with this: soup.find_all('div', {'class': 'lfloat'}, text=re.compile(r'(Fiscal|[^yeah])'))

(not sure here)

0


source







All Articles