简体   繁体   中英

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.

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.
  2. UIButton UIButton--hero are multiple class name values. To use them you need to use CSS_SELECTOR or XPATH, not CLASS_NAME since CLASS_NAME receives single value.

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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