我正在尝试使用 selenium 单击网站autotrader.co.uk的 cookie 弹出窗口上的“全部接受”或“全部拒绝”按钮,但由于某种原因我无法让弹出窗口消失。
这是弹出窗口:
这是 HTML:
<button title="Reject All" aria-label="Reject All" class="message-component message-button no-children focusable sp_choice_type_13" style="opacity: 1; padding: 10px 5px; margin: 10px 5px; border-width: 2px; border-color: rgb(5, 52, 255); border-radius: 5px; border-style: solid; font-size: 14px; font-weight: 400; color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; width: calc(35% - 20px); background: rgb(5, 52, 255);">Reject All</button>
我尝试过的代码如下:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
path_to_driver = r"C:\path_to_project\chromedriver.exe"
service = Service(executable_path=path_to_driver)
driver = webdriver.Chrome(service=service)
driver.get("https://www.autotrader.co.uk")
time.sleep(5)
WebDriverWait(driver, 15).until(EC.element_to_be_clickable((By.CLASS_NAME, 'message-component message-button no-children focusable sp_choice_type_13'))).click()
time.sleep(10)
driver.quit()
有人可以帮忙吗?
如您所见,弹出窗口嵌入在
<iframe>
Selenium 中,必须先将驱动程序的上下文切换到该 iframe,然后才能尝试定位或与其中包含的任何元素进行交互。等待所需的 iframe 元素可用以切换到它:
注意:由于
id
iframe 的属性似乎是动态生成的,因此建议使用部分匹配策略来定位 iframe,例如CSS selector
使用XPath
函数contains()
或部分匹配策略(https://stackoverflow.com/a/56844649/11179336)您可以这样做:
在 Selenium 中使用多个类名时,需要使用 CSS 选择器或 XPath 来代替 By.CLASS_NAME。因此,我在这里使用了:
编辑:
我没有使用
XPath
,因为如果我在这里(印度)打开网站,就不会弹出Cookie弹窗。请按照我已更正的以下代码操作XPath
。检查XPath
按钮的 并将其更改为实际的 即可。如果问题仍然存在,请检查 Cookie 内容是否在 iframe 中。如果是,请进行如下更改: