简体   繁体   English

Selenium 按钮单击无法使用 button.click()

[英]Selenium button click not working using button.click()

i was trying to load a page and press button, but it seems that i am doing something wrong.我试图加载一个页面并按下按钮,但似乎我做错了什么。 I used to know to these things but new selenium update made things more hard now.我以前知道这些事情,但现在新的 selenium 更新让事情变得更加困难。

here is the code.这是代码。

import selenium
from selenium import webdriver
import time
from selenium.webdriver.common.by import By



browser = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\chromedriver\chromedriver.exe")

driver = webdriver.Chrome()

driver.get("https://quizlet.com/217866991/match")

time.sleep(5)


button = browser.find_element(By.CLASS_NAME,"UIButton UIButton--hero")

# Click the button
button.click()

I tried many times to find solution but things did not work.我多次尝试寻找解决方案,但没有成功。

There are several issues here:这里有几个问题:

  1. You need use WebDriverWait expected_conditions instead of hardcoded delay.您需要使用WebDriverWait expected_conditions而不是硬编码延迟。
  2. UIButton UIButton--hero are multiple class name values. UIButton UIButton--hero多个class 名称值。 To use them you need to use CSS_SELECTOR or XPATH, not CLASS_NAME since CLASS_NAME receives single value.要使用它们,您需要使用 CSS_SELECTOR 或 XPATH,而不是 CLASS_NAME,因为 CLASS_NAME 接收单个值。

The following code works:以下代码有效:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("start-maximized")

webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)

url = "https://quizlet.com/217866991/match/"
driver.get(url)

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".UIButton.UIButton--hero"))).click()

The result screen is结果画面是

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM