Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2020-11-29 21:40:34

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()?

Questioner
Quanti Monati
Viewed
0
MendelG 2020-11-30 07:59:24

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"]'))