簡體   English   中英

在 Python 上使用 Selenium 在彈出窗口 Window 上找不到元素

[英]Can't locate element on Pop-Up Window using Selenium on Python

我想用這個 url: https://www.duden.de/rechtschreibung/aussuchen從 Duden 網頁上抓取一些元素。 當我手動查找頁面時,不會出現彈出窗口,但是當我在 python 上使用 selenium 時,會出現這種情況:彈出窗口的圖像

我已經嘗試了很多東西,比如阻止彈出窗口,或者嘗試點擊接受按鈕。 所有這些都不起作用。

我試圖找到框架的一個元素並打印一條語句,然后查看它是否可以找到這些元素,但這也不起作用。

有誰知道為什么會這樣或者我可以嘗試更多嗎?

這些是我嘗試過的一些事情:

  • 對於阻塞:

     def getAllWordForms(word): options = Options() profile = webdriver.FirefoxProfile() profile.set_preference("dom.disable_open_during_load", False) driver = webdriver.Firefox(firefox_profile=profile,options=options, executable_path=os.path.join(driver_location, 'geckodriver')) main_url = 'https://www.duden.de/rechtschreibung/' word_url = main_url + '{}'.format(word) driver.get(word_url)
  • 看看它是否可以在彈出框中找到一個元素:

     def getAllWordForms(word): options = Options() driver = webdriver.Firefox(options=options, executable_path=os.path.join(driver_location, 'geckodriver')) main_url = 'https://www.duden.de/rechtschreibung/' word_url = main_url + '{}'.format(word) driver.get(word_url) driver.implicitly_wait(10) driver.switch_to.frame(1) if driver.find_elements_by_class_name('message-button'): print('yes')
  • 點擊按鈕:

     def getAllWordForms(word): options = Options() options.headless = False driver = webdriver.Firefox(options=options, executable_path=os.path.join(driver_location, 'geckodriver')) main_url = 'https://www.duden.de/rechtschreibung/' word_url = main_url + '{}'.format(word) driver.get(word_url) driver.implicitly_wait(10) driver.switch_to.frame(1) button = driver.find_element_by_xpath("//button[@aria-label='AKZEPTIEREN']") button.click() driver.switch_to.default_content()

我嘗試了各種組合,但它從來沒有奏效。

頁面的元素結構如下: page_1的結構page_2 的結構

希望我能正確解釋它,也許有人可以幫助我。

每次啟動 webdriver 時,您都在使用新的臨時配置文件。 該配置文件沒有 cookies 因此站點將其視為需要接受 cookie 消息的新用戶。

我查看了您的站點並關閉了您需要切換 iframe 的消息。 你對你的解決方案很接近,它可能只是需要一種不同的選擇框架的方法......

這段代碼對我有用:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.duden.de/rechtschreibung/aussuchen")

iframe = driver.find_element_by_xpath("//iframe[contains(@id,'sp_message_iframe')]")
driver.switch_to.frame(iframe)
cookieAccpet = WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='AKZEPTIEREN']")))
cookieAccpet.click()

driver.switch_to.default_content()

記得在最后用driver.switch_to.default_content()切換回默認幀,然后你可以繼續你的腳本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM