[英]Python and Selenium: Locating and clicking a button for cookies within an iframe
任何人都有一个解决方案来定位网页中的按钮,并带有一个重叠的弹出窗口 window,如下例所示:
from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'./geckodriver')
driver.get("https://www.academics.de/")
#after waiting for a while the popup window comes up
driver.find_elements_by_xpath("//*[contains(text(), 'Zustimmen')]")
返回的列表为空。 运行以下
driver.find_element_by_css_selector(".button-accept")
结果是:
NoSuchElementException: Message: Unable to locate element: .button-accept
这可能会有所帮助。
executable_path = r"C:\\Users\\Selenium+Python\\geckodriver.exe"
options.add_experimental_option("prefs", {"profile.default_content_setting_values.notifications": 2})
options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})
options.add_argument("start-maximized")
driver = webdriver.Chrome(executable_path, options=options)
文本为E-Mail Login的元素位于iframe中,因此您必须:
诱导WebDriverWait使所需的帧可用并切换到它。
诱导WebDriverWait使所需元素成为可点击的。
您可以使用以下任一定位器策略:
使用CSS_SELECTOR
:
driver.get("https://www.academics.de/") WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='SP Consent Message']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='Zustimmen']"))).click()
使用XPATH
:
driver.get("https://www.academics.de/") WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='SP Consent Message']"))) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='Zustimmen']"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到一些相关的讨论:
解决您的问题的一个简单方法是在您的 Selenium 实例上使用uBlock Origin扩展 + Fanboy 的烦恼阻止列表,这样这些烦人的 cookies 消息就不会出现。 此 StackOverflow 答案中描述了一种启用扩展的方法:
- 通过右键单击 windows 开始按钮 > 运行 > firefox.exe -P 创建一个新的 firefox 配置文件
- 然后添加你想要的任何扩展,ublock,adblock plus 等
- 调用您的个人资料文件夹
profile = selenium.webdriver.FirefoxProfile("C:/test")
browser = selenium.webdriver.Firefox(firefox_profile=profile, options=ops)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.