3

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.

    2 Answers 2

    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 
    1
    • Thank you :). I wish I can know how to use ~= correctly. After reading the descriptions at w3schools.com, I cannot tell the difference between ~= and *=.
      – Brian
      CommentedDec 26, 2015 at 8:12
    1

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

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.