繁体   English   中英

如何使用 Selenium 和 Python 在 xpath 中相对于变量定位元素

[英]How to locate an element with respect to a variable within a xpath using Selenium and Python

size = '19'

driver.find_element_by_xpath('//a[@title="Sélectionner Taille:" + size]').click()

这是我的代码,但它不起作用,因为 ' 将变量卡在一个简单的引号中,所以我不知道该怎么做,请帮助我,我将 selenium 与 python 一起使用到 chrome 驱动程序中

试试这个它会帮助你。

driver.find_element_by_xpath("//a[@title="Sélectionner Taille:"'" + size + "']").click()

您也可以参考这个答案: link

如果没有 HTML ,则不清楚Sélectionner Taille:19之间的空白数量。 因此,使用Selenium对元素调用click()进行折扣,您需要为element_to_be_clickable()诱导WebDriverWait ,您可以使用以下任一定位器策略

  • XPATH中使用变量:

     size = '19' WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '" +size+ "')]"))).click()
  • XPATH中使用%s

     size = '19' WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '%s')]"% str(size)))).click()
  • XPATH中使用format()

     size = '19' WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[starts-with(@title, 'Sélectionner Taille') and contains(@title, '{}')]".format(str(size))))).click()
  • 注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

参考

您可以在以下位置找到一些相关的讨论:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM