[英]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.