【问题标题】:Selenium Can't find element when using find_element through Python通过Python使用find_element时Selenium找不到元素
【发布时间】:2019-04-29 02:21:47
【问题描述】:

不断收到unable to locate element 错误消息。

xpath 的第一个查找元素很好,但第二个让我很难。

这是我的代码:

import XLUtils
from selenium import webdriver

driver=webdriver.Chrome(executable_path="C:\Chrome_Driver\Chromedriver.exe")
driver.get("https://www.canada.ca/en/revenue-agency/services/e-services/e-services-businesses/payroll-deductions-online-calculator.html")

driver.find_element_by_xpath('/html/body/main/div[1]/div[7]/p/a[1]').click()
driver.find_element_by_xpath('//*[@id="welcome_button_next"]').click()

【问题讨论】:

  • 您不想使用具有那么多级别或索引的 XPath,因为这会使它们变得脆弱(更容易损坏)。更好的第一个定位器是 CSS 选择器,a.btn-primary。对于第二个定位器,当您只有一个 ID 时,不要通过 XPath 查找。而是使用.find_element_by_id("welcome_button_next").
  • 另外,您需要将相关的 HTML 添加到问题中。提供链接很好,但如果 HTML 将来发生变化,这个问题将没有用,也不能独立存在。

标签: python selenium xpath css-selectors webdriverwait


【解决方案1】:

您需要稍等片刻,Next 按钮才会出现。

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

wait = WebDriverWait(driver, 10)

e = wait.until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="welcome_button_next"]'))
    )
e.click()

【讨论】:

  • 你不想在这里等待出现然后点击。 Presence 表示元素在 DOM 中,但不一定可见或可点击。相反,您希望等待可点击。
  • 感谢您的评论!真的很感激!
【解决方案2】:

要单击文本为 Next 的元素,您需要诱导 WebDriverWait 以使 元素可点击,您可以使用以下解决方案:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.btn.btn-primary#welcome_button_next"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='btn btn-primary' and @id="welcome_button_next"]"))).click()
    
  • 注意:您必须添加以下导入:

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

【讨论】:

  • 与其用更多与现有答案几乎完全相同的答案“垃圾邮件”问题,不如您帮助纠正其他接近完美的答案?
  • 感谢您的评论!真的很感激!
猜你喜欢
  • 1970-01-01
  • 2021-10-18
  • 2021-06-22
  • 1970-01-01
  • 2021-03-20
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多