我正在尝试关闭网站上的 Cookie 同意弹出窗口 https://www.meinschiff.com/。我使用 chrome 的 selenium webdriver 来查找关闭并接受 div 元素,然后单击先找到的那个。如果我手动选择拒绝按钮,那么它会关闭,但会因加载另一层而挂起。该元素的父级 div 元素的 id="blur" 充当不断加载的覆盖层。该代码首先获取接受按钮并单击它,但它刷新页面并给出 StaleElementReference 错误。当我在普通 Chrome 浏览器中打开该网站时,点击效果非常好。 我想点击接受按钮并关闭弹出窗口。
我的代码:
div_elements = WebDriverWait(driver,
5).until(EC.presence_of_all_elements_located((By.TAG_NAME, "div")))
for div_element in div_elements:
try:
element_html = div_element.get_attribute("outerHTML")
div_element_attrs = BeautifulSoup(element_html, "lxml").div.attrs
# class_attr = div_element.get_attribute('class')
# title_attr = div_element.get_attribute('title')
value_attr = div_element.get_attribute('value')
popup_div = False
for key in div_element_attrs.keys():
if any(keyword in (div_element.get_attribute(key) or '').lower()
for keyword in close_keywords) or \
(value_attr is not None and value_attr.lower() == 'false'):
print("closing div pop-up...")
popup_div = True
break
else:
if any(keyword in (div_element.get_attribute(key) or
'').lower() for keyword in accept_keywords) or \
(value_attr is not None and value_attr.lower() == 'false'):
print("accepting div pop-up...")
popup_div = True
break
if popup_div:
ActionChains(driver).move_to_element(div_element).click().perform()
time.sleep(2)
if div_element.is_displayed():
print("div element not closed")
return False
else:
print("div element closed")
return True
except ElementClickInterceptedException:
print(f"Div Element click intercepted:
{div_element.get_attribute('outerHTML')}")
continue
except Exception as e:
print(f"Error processing div element: {e}")
continue
我也尝试过 javascript 点击:
driver.execute_script("arguments[0].scrollIntoView(true);", div_element)
driver.execute_script("arguments[0].click();", div_element)
并等待元素可点击,它会导致相同的行为:
clickable_element = WebDriverWait(driver,
10).until(EC.element_to_be_clickable(div_element))
ActionChains(driver).move_to_element(clickable_element).click().perform()
我不知道我是否真正理解你的帖子,但就像 @browsermator 所说的那样,这似乎是一个时间问题。
您可以使用隐式等待:Selenium-python 文档
5.2。隐式等待 隐式等待告诉 WebDriver 在尝试查找任何元素(或 元素)不能立即可用。默认设置为 0(零)。 设置后,隐式等待将在 WebDriver 的生命周期内设置 对象。
from selenium import webdriver driver = webdriver.Firefox() driver.implicitly_wait(10) # seconds driver.get("http://somedomain/url_that_delays_loading") myDynamicElement = driver.find_element_by_id("myDynamicElement")
下面的脚本启动驱动程序,设置隐式等待10秒,转到meinschiff网页,拒绝cookie并打印meinschiff的口号:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# Create a new instance of the Chrome driver
driver = webdriver.Chrome()
driver.implicitly_wait(10)
# Open the website
driver.get('https://www.meinschiff.com/')
try:
# Close and refuse cookies
driver.find_element(By.ID, "privacy_pref_optout").click()
# Print the slogan in the webpage
slogan = driver.find_element(By.ID, "html")
print(slogan.text)
except Exception as e:
print(e)
希望对您有帮助。如果您的问题已解决,请随时告诉我们。