【问题标题】:Click “Accept Cookies” popup with Selenium in Python在 Python 中使用 Selenium 单击“接受 Cookie”弹出窗口
【发布时间】:2021-07-20 07:06:57
【问题描述】:

我一直在尝试用 selenium 抓取这个电子商务网站的一些信息。但是,当我访问该网站时,我需要接受 cookie 才能继续。这只发生在机器人访问网站时,而不是我手动访问时。当我尝试通过 xpath 找到相应的元素时,当我手动检查页面时找到它时,我总是收到以下错误消息:

selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attach to the page document

我的代码如下所示。

import time
import pandas
pip install selenium
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup #pip install beautifulsoup4

PATH = "/Users/Ziye/Desktop/Python/chromedriver"
delay = 15

driver = webdriver.Chrome(PATH)
driver.implicitly_wait(10)

driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()

这是与“没关系”按钮对应的 HTML。 XPATH 同上。

<button aria-label="" id="uc-btn-accept-banner" class="uc-btn uc-btn-primary">
                          That’s OK <span id="uc-optin-timer-display"></span>
                      </button>

有人知道我的错误在哪里吗?

【问题讨论】:

    标签: python selenium selenium-webdriver cookies


    【解决方案1】:

    你应该为这个按钮添加明确的等待:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    
    driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
    driver.implicitly_wait(10)
    
    driver.get("https://en.zalando.de/women/?q=michael+michael+kors+taschen")
    wait = WebDriverWait(driver, 15)
    wait.until(EC.element_to_be_clickable((By.XPATH, '//*[@id="uc-btn-accept-banner"]')))
    driver.find_element_by_xpath('//*[@id="uc-btn-accept-banner"]').click()
    

    您的定位器是正确的。 作为css选择器,你可以使用.uc-btn-footer-container .uc-btn.uc-btn-primary

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多