Quanti Monati
Quanti Monati

Reputation: 811

How to select all elements based on alternative attributes? [BeautifulSoup]

I have to select all html-tags that has class attribute if the class name is in list OR has a style attribute with the specified value.

I tried to solve my problem step by step and I got this:

selected_by_class = soup.find_all(class_=['basic_class', 'other_class'])
selected_by_style = soup.find_all(style='text-align:left')

As you can see, I'm getting all the data in two steps, but the sequence is lost, because I do two independent find_all() requests.

How to do it simultaneously with a single find_all()?

Upvotes: 2

Views: 586

Answers (1)

MendelG
MendelG

Reputation: 20008

Try using CSS Selectors. To use multiple Selectors, separate them with a comma ,.

To use a CSS Selector for a classname, use: .<classname>

To use a CSS Selector for the style, you can use the [attribute="value"] Selector.

So in your example:

[..]

# Using multiple CSS Selectors - separated by a comma.
print(soup.select('.class1, .class2, [style="text-align:left"]'))

Upvotes: 3

Related Questions