问题
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.
回答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
回答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\"]')
来源:https://stackoverflow.com/questions/34469504/selenium-find-elements-by-css-selector-returns-an-empty-list