如何使用Selenium和Python定位xpath中与变量相关的元素

2024-09-26 17:56:53 发布

您现在位置:Python中文网/ 问答频道 /正文

size = '19'

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

这是我的代码,但它不能作为“将变量粘贴到简单的引号中”来工作 所以我不知道该怎么办,请帮帮我 我在chrome驱动程序中使用selenium和python


Tags: 代码sizebytitle粘贴driverelementfind
2条回答

如果没有HTML,就不清楚Sélectionner Taille:19之间的空格数量。因此,对于使用Selenium调用元素上的click()的所有空格,您需要为element_to_be_clickable()推导WebDriverWait,并且可以使用以下任意一种Locator Strategies

  • 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
    

参考文献

您可以在以下内容中找到一些相关讨论:

try this it will help you.

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

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

相关问题 更多 >

    热门问题