Webscraping Selenium / 处理 PopUp-Windows?

Webscraping Selenium / Handling PopUp-Windows?

,我尝试从网站上抓取一些东西,到目前为止效果很好 - 但在(匿名)selenium windows 中,每次都会弹出一条消息,我必须手动处理。到目前为止,我无法将其自动化。

留言:https://drive.google.com/file/d/1QAtMuzimJ3bLOfVEJY2M65S32nvc1Ewb/view?usp=sharing

通常我可以在复制 xpath 时单击按钮,例如:

driver.find_element_by_xpath ('//*[@id="example-blabla"]').click ()

但在那种情况下,它不适用于此弹出窗口-windows - xpath 看起来有点不同...

driver.find_element_by_xpath ('/html/body/div/div[3]/div[3]/div[2]/button').click ()

也尝试使用 window_handles 但这也不起作用...您可以在下面找到完整的代码

from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import time
import os


options = Options ()
#options.add_argument ('--headless')
options.add_experimental_option ('excludeSwitches', ['enable-logging'])
driver = webdriver.Chrome (os.getcwd () + '/chromedriver.exe', options=options)

link = "https://www.finanzen.net"
driver.get (link)
time.sleep (5)

a = driver.window_handles
print(a[0])
driver.switch_to.window(a[0])
driver.find_element_by_xpath ('/html/body/div/div[3]/div[3]/div[2]/button').click ()

driver.quit()

更新 - 能够找到如下对我有用的解决方案:

代码如下:

link = "https://www.finanzen.net"
driver.get (link)
time.sleep (5)
act_window = driver.current_window_handle
driver.switch_to.frame ("sp_message_iframe_213940")
time.sleep (3)
driver.find_element_by_xpath
('/html/body/div/div[3]/div[3]/div[2]/button').click ()
print("Message should disappeared...")
time.sleep (3)
driver.switch_to.window(act_window)
print("Hurra!...")

存在于 iframe 中的元素。您需要先切换 iframe 才能访问按钮元素。

诱导WebDriverWait()等待frame_to_be_available_and_switch_to_it() 和以下 css 选择器。

诱导WebDriverWait()等待element_to_be_clickable() 并遵循 xpath。

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='sp_message_iframe']")))
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[text()='OK und Weiterlesen']"))).click()

导入以下库

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