【问题标题】:Trouble using selenium to click an item by partial link text使用 selenium 通过部分链接文本单击项目时遇到问题
【发布时间】:2019-09-04 15:44:44
【问题描述】:

所以几年前我编写了一个脚本,该脚本将使用 selenium 导航商店,按名称定位商品,然后选择它们。我试图重新使它查看我的旧代码,但它的工作方式不一样。我正在尝试使用 selenium 单击它找到的第一个项目,其中包含当我在项目上使用检查元素时它们拥有的文本。但是,我只是不断收到相同的错误,即找不到包含该文本的元素。

from selenium import webdriver

driver=webdriver.Chrome('fakepath/fake')
driver.get("https://www.supremenewyork.com/shop/all")

driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click()
driver.find_element_by_partial_link_text('GORE-TEX')

这是包含我尝试使用 selenium 查找并单击的文本的元素

<a class="name-link" href="/shop/jackets/g1ze294ol/qapno01c2">GORE-TEX Taped Seam Jacket</a>
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"GORE-TEX"}
  (Session info: chrome=76.0.3809.132)

【问题讨论】:

    标签: python html css selenium selenium-chromedriver


    【解决方案1】:

    您需要等到元素可点击。这将点击页面上的第一个匹配链接。

    from selenium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    
    
    driver.get("https://www.supremenewyork.com/shop/all")
    driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click()
    
    link = WebDriverWait(driver,15).until(EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "GORE-TEX")))
    link.click()
    time.sleep(3)
    

    【讨论】:

      【解决方案2】:

      当执行driver.find_element_by_xpath("//a[@href='/shop/all/jackets']").click() 行时,您尝试单击的元素尚未准备好被单击。换句话说,您需要等到元素加载完毕。

      幸运的是,Selenium 允许您等待某些条件,例如“可点击”。参考here。

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      
      driver=webdriver.Chrome('fakepath/fake')
      wait = WebDriverWait(driver, 10)
      
      driver.get("https://www.supremenewyork.com/shop/all")
      
      try:
          wait.until(EC.element_to_be_clickable((By.XPATH, "//a[@href='/shop/all/jackets']")).click()
          driver.find_element_by_partial_link_text('GORE-TEX')
      finally:
          driver.quit()
      
      

      【讨论】:

      • 在你的wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="Some text"]'))).click() 行中,你有“一些文本”的地方会写什么,或者该行会取代我用于选择夹克类别的行?
      • 正确,感谢您的理解。我编辑了响应以反映您的 XPATH。
      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 2019-08-02
      • 1970-01-01
      • 2020-11-15
      相关资源
      最近更新 更多