首页 > 解决方案 > 如何定位这个元素?

问题描述

我想找到“下一步”按钮。按类名定位不起作用,因为存在具有相同类名的其他元素。此按钮没有 ID。

我尝试通过 xpath>>contains text 等进行定位,它可以工作。但这不是完美的方式,由于该站点可能在未来进行翻译,并且“NEXT”文本可能看起来完全不同......它大约是最后两行。

https://imgur.com/a/N6RK4Hh

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()

标签: pythonseleniumxpathcss-selectorswebdriverwait

解决方案


使用WebDriverWaitandelement_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)

推荐阅读