Selenium find_elements_by_css_selector returns an empty list

10,103

Solution 1

Selenium CSS only support three partial match operators viz.- $^*.

CSS partial match expression is not correct- Use * or ^ details at here and here. You can use xpath too.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://udemycoupon.discountsglobal.com/coupon-category/free-2/")

#select by css
#try *
css_lnks = [i.get_attribute('href') for i in driver.find_elements_by_css_selector('[id*=coupon-link]')]
#or try ^
#css_lnks = [i.get_attribute('href') for i in driver.find_elements_by_css_selector('[id^=coupon-link]')]

#select by xpath
xpth_lnks = [i.get_attribute('href') for i in driver.find_elements_by_xpath("//a[contains(@id,'coupon-link-')]")]

print xpth_lnks
print css_lnks

Solution 2

The ~= selector selects by value delimited by spaces. In that sense, it works similarly to a class selector matching the class attribute.

Since IDs don't usually have spaces in them (because an id attribute can only specify one ID at a time), it doesn't make sense to use ~= with the id attribute.

If you just want to select an element by a prefix in its ID, use ^=:

elems = driver.find_elements_by_css_selector('[id^=\"coupon-link\"]')
Share:
10,103
Brian
Author by

Brian

Welcome to visit my blog. If you find my questions or answers useful, you can support me by registering honeygain with my referral link.

Updated on June 05, 2022

Comments

  • Brian
    Brian almost 2 years

    I'm trying to select all the ids which contain coupon-link keyword with the following script.

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.Firefox()
    driver.get("http://udemycoupon.discountsglobal.com/coupon-category/free-2/")
    elems = driver.find_elements_by_css_selector('[id~=\"coupon-link\"]')
    print(elems)
    

    But I got an empty list [] as the result. What's wrong with my css_selector?

    I've tested that find_elements_by_css_selector('[id=\"coupon-link-92654\"]') works successfully. But I want to select all the coupon-links, not just one of them.

    I referenced the document at w3schools.com.