python - 如何定位这个元素?
问题描述
我想找到“下一步”按钮。按类名定位不起作用,因为存在具有相同类名的其他元素。此按钮没有 ID。
我尝试通过 xpath>>contains text 等进行定位,它可以工作。但这不是完美的方式,由于该站点可能在未来进行翻译,并且“NEXT”文本可能看起来完全不同......它大约是最后两行。
from time import sleep
import self as self
from selenium import webdriver
from selenium.common.exceptions import ElementClickInterceptedException, StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path="C:\Chromedriver\chromedriver.exe")
driver.implicitly_wait(1)
driver.get("https://cct-103.firebaseapp.com/")
try:
checkin = WebDriverWait(driver, 1).until(EC.element_to_be_clickable((By.CLASS_NAME, "MuiButton-label")))
checkin.click()
except StaleElementReferenceException:
checkin = WebDriverWait(driver, 1).until(EC.element_to_be_clickable((By.CLASS_NAME, "MuiButton-label")))
checkin.click()
locator = (By.ID, "guestName")
guest_input = driver.find_element(*locator)
guest_input.send_keys("xyz")
next_button = driver.find_element_by_xpath("//*[contains(text(), 'NEXT')]")
next_button.click()
解决方案
使用WebDriverWait
andelement_to_be_clickable
和以下定位器选项。
next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(., 'NEXT')]")))
next_button.click()
有时你可能会被截获异常。
next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(., 'NEXT')]")))
driver.execute_script("arguments[0].click();", next_button)
使用 Css 选择器更新了代码。
next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button.MuiButtonBase-root")))
next_button.click()
或者
next_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button.MuiButtonBase-root")))
driver.execute_script("arguments[0].click();", next_button)
推荐阅读
- haskell - 在 Haskell 服务端中进行客户端绑定 - ConnectionError
- angular - 如何在 NgFor 循环中以角材料的每行显示最多 5 张卡片
- c# - Winforms:运行 oledb 连接时出错(可安装的 Isam,未为命令对象设置 Commandtext)
- uwp - UWP C# UART RS485 通信问题
- c - 带有管道到文件的 Echo 服务器
- vuejs2 - 防止 el-menu-item 在单击时添加“is-active”类
- tar - tar.bz2 无法统计:没有这样的文件或目录
- node.js - Angular 通用 - 运行 node.js 时出现警告
- php - 如何在 laravel spatie 中更新/编辑 custom_properties?
- javascript - 如何延迟/开始/去抖动获取数据,直到用户停止输入?