我正在嘗試單擊此網站https://www.soccerstats.com/matches.asp?matchday=1#上的“同意”按鈕,但使用此代碼對我不起作用:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
s=Service("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
driver=webdriver.Chrome(service=s)
driver.get("https://www.soccerstats.com/matches.asp?matchday=1#")
driver.maximize_window()
time.sleep(1)
driver.find_element(By.CLASS_NAME," css-47sehv").click()
這css-47sehv是按鈕的類名,這是按鈕的圖片藍色按鈕
uj5u.com熱心網友回復:
盡管該元素AGREE包含 classname css-47sehv,但該值看起來是動態的,并且可能會在短時間內或應用程式重新啟動后發生變化。
解決方案
要單擊元素,您需要為element_to_be_clickable()誘導WebDriverWait,您可以使用以下任一定位器策略:
使用CSS_SELECTOR:
driver.get("https://www.soccerstats.com/matches.asp?matchday=1#") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[mode='primary']"))).click()使用XPATH:
driver.get("https://www.soccerstats.com/matches.asp?matchday=1#") WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@mode='primary' and text()='AGREE']"))).click()注意:您必須添加以下匯入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
uj5u.com熱心網友回復:
嘗試使用這個
driver.find_element_by_class_name('css-47sehv').click()
代替
driver.find_element(By.CLASS_NAME," css-47sehv").click()
uj5u.com熱心網友回復:
要單擊AGREE按鈕,請使用以下xpath標識元素并單擊。
//button[text()='AGREE']
代碼:
driver.find_element(By.XPATH,"//button[text()='AGREE']").click()
或使用以下 css 選擇器。
driver.find_element(By.CSS_SELECTOR,"button.css-47sehv").click()
uj5u.com熱心網友回復:
您必須確保以下幾點:
1-使用明確等待按鈕到/直到出現
try:
element=WebDriverWait(driver,10).until(
EC.presence_of_element_located((By.ID, "AgreeButton"))
)
finally:
driver.quit()
2-單擊具有正確 Xpath 的按鈕:
driver.find_element(By.XPATH,"//button[text()='AGREE']").click()
3-如果簡單點擊不起作用,您可以使用 JavaScript 并執行點擊方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/464528.html
