OR condition in CSS Selector with Selenium/Python

Question:

I hope you’re fine.

I’m scraping the logos of some websites. I’m using the next code to localize them. I don’t use a tag only the * because the class or attribute that contains the substring ‘logo’ there is not always in a <div> or <a> tags.

driver.find_element(By.CSS_SELECTOR, "*[class*='logo']")

I have obtained some of them but in some cases the ‘class’ doesn’t have the substring ‘logo’. I’ve checked some websites and the logo has attributes like ‘id’, ‘alt’ or ‘name’ that contains the substring ‘logo’.

So I want to know if is there some condition like OR to applied it and if there is no match with ‘class’ then check in ‘id’, etc.

I tried with these options but both launch an error:

driver.find_element(By.CSS_SELECTOR, "*[class*='logo'] | *[id*='logo']")
driver.find_element(By.CSS_SELECTOR, "*[class*='logo'] || *[id*='logo']")

In both cases the error is:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: An invalid or illegal selector was specified
Asked By: Marcos Arreguín

||

Answers:

You can use , to group multiple CSS selectors.

driver.find_element(By.CSS_SELECTOR, "[class*='logo'], [id*='logo']")
Answered By: Unmitigated

If you are not specific about using CSS_SELECTOR, you can try using XPATH as below:

//*[@*='logo']

Code should be:

driver.find_element(By.XPATH, "//*[@*='logo']")

This XPath expression will search the entire DOM(//*) for all attributes(@*) like class,id,name etc. which has the value =logo

Answered By: Shawn