首页 > 解决方案 > 在 python 中使用 selenium 使用 xPath 查找元素的问题

问题描述

我想登录页面并单击位于网站顶部的按钮,但是当我运行代码时它说找不到元素,下面是我的 python 代码:

from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://go.xero.com/Dashboard")
user_name = driver.find_element_by_id("email")
user_name.send_keys("mnb@allied.ae")
password = driver.find_element_by_id("password")
password.send_keys()
Submit = driver.find_element_by_id("submitButton")
Submit.click()
CS = driver.find_element_by_xpath("//span[@class='xrh-appbutton--text']")
cs.click()

driver.quit() 

下面是 HTML 源代码:

在此处输入图像描述

标签: pythonseleniumselenium-webdriverautomated-tests

解决方案


似乎需要一些时间才能找到元素。要管理它,您需要在脚本中实现等待机制。使用隐式或显式等待。参考这个

隐式等待

driver.get("https://go.xero.com/Dashboard")
driver.implicitly_wait(15)

显式等待

cs = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@class='xrh-appbutton--text']")))
cs.click()

为此需要导入以下包 -

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

推荐阅读