如何在Python中使用Selenium接受Cookie警报

2024-10-01 13:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图进入google.com并在搜索栏中键入一些内容。但是cookies alert弹出窗口总是挡住我的路。所以我必须点击“我同意”按钮。我知道在搜索元素之前我必须等待一点时间,但即使我使用WebDriverWait()函数或.implicitly_wait()等待,它也不想找到元素(我使用xpath搜索和.click()按下按钮)。 花了几个小时试图找到解决方案

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

def main():
    driver = webdriver.Chrome('chromedriver.exe')
    url = 'https://www.google.com/'
    driver.get(url)
 
    # The following line is supposed to wait for the button to appear and then click:
    agreeButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='introAgreeButton']")))
    agreeButton.click()

main()

此外,我还应在此处包括错误:

Traceback (most recent call last):

File "{SCRIPT PATH}", line 49, in <module>
    
     main()

File "{SCRIPT PATH}", line 46, in main

   agreeButton = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//*[@id='introAgreeButton']")))

File "C:\ProgramData\Anaconda3\lib\site-packages\selenium\webdriver\support\wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)

selenium.common.exceptions.TimeoutException: Message: 

Tags: fromimportsupportbymaindriverseleniumline