Selenium技术问题:如何定位并点击指定的登录按钮
解决Selenium点击MUI登录按钮失败的问题
问题背景
尝试点击页面中的登录按钮,按钮HTML结构如下:
<button class="MuiButton-root MuiButton-contained MuiButton-containedPrimary MuiButton-sizeMedium MuiButton-containedSizeMedium MuiButtonBase-root css-1rs4rtx" tabindex="0" type="button"> Zaloguj się<span class="MuiTouchRipple-root css-w0pj6f"></span></button>
已尝试的代码:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC # Web credentials username = "qwerty@gmail.com" password = "qwerty" # Initialize the Chrome driver driver = webdriver.Chrome("chromedriver") # Head to login page driver.get("https://tzgirls.app/login") # Find username/email field and send the username itself to the input field driver.find_element("id", "login_email").send_keys(username) # Find password input field and insert password as well driver.find_element("id", "login_password").send_keys(password) #import time #time.sleep(2) wait = WebDriverWait(driver, 20) wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(),'Zaloguj się')]"))).click()
可行解决方法
方法1:利用MUI固定类名定位
MUI按钮的核心类名不会随动态CSS变化,用组合类名定位更稳定:
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.MuiButton-containedPrimary.MuiButton-contained"))).click()
方法2:处理文本空格后精确匹配
原XPAHT失效可能是因为文本前有空格,用normalize-space处理空格后定位:
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space(text())='Zaloguj się']"))).click()
方法3:属性+文本组合定位
同时指定按钮的type属性和文本,进一步缩小定位范围:
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@type='button' and normalize-space(text())='Zaloguj się']"))).click()
方法4:JavaScript强制点击
如果元素已加载但Selenium无法触发点击,直接用JS执行点击操作:
button = wait.until(EC.presence_of_element_located((By.XPATH, "//button[normalize-space(text())='Zaloguj się']"))) driver.execute_script("arguments[0].click();", button)
额外注意事项
- 确保ChromeDriver版本与本地Chrome浏览器版本完全匹配,版本不兼容会导致元素交互异常
- 若页面存在弹窗、iframe,需先切换到对应上下文再定位按钮
- 可添加
driver.maximize_window(),避免按钮被视图边缘遮挡无法点击
内容的提问来源于stack exchange,提问作者Paulina
相关产品推荐
相关产品推荐

