无法在 Python 上使用 Selenium 定位弹出窗口上的元素

kim*_*kim 5 python selenium popup blocking

我想使用以下网址从 Duden 网页中抓取一些元素:https://www.duden.de/rechtschreibung/aussuchen。当我手动查找页面时,不会出现弹出窗口,但是当我在 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)
    
    Run Code Online (Sandbox Code Playgroud)
  • 查看是否可以在弹出框架中找到元素:

    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')
    
    Run Code Online (Sandbox Code Playgroud)
  • 单击按钮:

      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()
    
    Run Code Online (Sandbox Code Playgroud)

我尝试了各种组合,但从来没有奏效。

页面元素的结构如下: page_1 的结构 page_2 的结构

希望我能正确解释,也许有人可以帮助我。

Ric*_*rds 1

每次启动网络驱动程序时,您都在使用新的临时配置文件。该配置文件没有 cookie,因此站点将其视为新用户,需要接受 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()
Run Code Online (Sandbox Code Playgroud)

请记住在最后使用 切换回默认帧driver.switch_to.default_content(),然后您可以继续编写脚本。