1

我是 python 和 selenium 的新手,我需要帮助。我不能在 iframe 中接受 cookie

任何人都可以帮助我吗?

谢谢

from selenium.webdriver.firefox.options import Options
from seleniumwire import webdriver

options = Options()
options.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'

driver = webdriver.Firefox(executable_path=r'C:\\geckodriver.exe', firefox_options=options)


driver.get('https://autoscout24.de/')
time.sleep(5)
# go to iframe accept cookies
driver.switch_to.frame("gdpr-consent-notice")
driver.find_element_by_css_selector("button[class='mat-focus-indicator solo-button mat-button mat-button-base mat-raised-button cdk-focused cdk-mouse-focused'] div[class='action-wrapper']").cick()



# back to previous frame
driver.switch_to.parent_frame()
time.sleep(5)


driver, quit()
4

1 回答 1

0

我看到ID是唯一的,那么您根本不需要CSS Selector

您应该诱导显式等待切换到iframe.

它们允许您的代码暂停程序执行或冻结线程,直到您通过它的条件得到解决。条件以一定的频率被调用,直到等待超时。这意味着只要条件返回一个虚假值,它就会继续尝试和等待。

代码 :

driver = webdriver.Firefox(executable_path=r'C:\\geckodriver.exe', firefox_options=options)
driver.maximize_window()
wait = WebDriverWait(driver, 20)
driver.get('https://autoscout24.de/')
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "gdpr-consent-notice")))
button = driver.find_element_by_id('save')
driver.execute_script("arguments[0].click();", button)


# back to previous frame
driver.switch_to.parent_frame()
time.sleep(5)

进口:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
于 2021-10-03T15:59:29.923 回答