我正在尝试使用以下脚本选择所有包含 coupon-link 关键字的 ID。
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)
但是我得到了一个空列表 [] 作为结果。我的 css_selector 有什么问题?
我已经测试过 find_elements_by_css_selector('[id=\"coupon-link-92654\"]') 可以成功运行。但我想选择所有优惠券链接,而不仅仅是其中一个。
我在 w3schools.com 引用了文档.
请您参考如下方法:
Selenium CSS 仅支持三个部分匹配运算符,即 - $^*。
CSS 部分匹配表达式不正确 - 使用 * 或 ^ 详情请见 here和 here .您也可以使用 xpath。
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
