Search code examples
pythonselenium-webdriverxpathscreen-scraping

OR condition in CSS Selector with Selenium/Python


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

Solution

  • You can use , to group multiple CSS selectors.

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