Python 3.5-Selenium-如何处理新窗口并等待其完全加载? [英] Python 3.5 - Selenium - How to handle a new window and wait until it is fully loaded?

查看:467
本文介绍了Python 3.5-Selenium-如何处理新窗口并等待其完全加载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行浏览器自动化,但在某个时候被阻止:稍后,我要求浏览器单击一个按钮,该按钮又打开一个新窗口.但是有时候Internet太慢了,因此这个新窗口需要花费一些时间来加载.我想知道如何让Selenium等待,直到这个新的新窗口完全加载.

I am doing browser automation and I am blocked at a certain point: at a moment, I ask the browser to click on a button, which in turn open up a new window. But sometimes the Internet is too slow, and so this new window takes time to load. I want to know how can I ask Selenium to wait until this new fresh window is fully loaded.

这是我的代码:

driver.switch_to.default_content()
Button = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, 'addPicturesBtn')))
Button.click()
newWindow = driver.window_handles
time.sleep(5)
newNewWindow = newWindow[1]
driver.switch_to.window(newNewWindow)
newButtonToLoad = driver.find_element_by_id('d')
newButtonToLoad.send_keys('pic.jpg')
uploadButton = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, 'uploadPics')))
uploadButton.click()
driver.switch_to.window(newWindow[0])

我有时会收到此错误:

newNewWindow = newWindow [1]

newNewWindow = newWindow[1]

IndexError:列表索引超出范围

IndexError: list index out of range

这使我认为简单的"time.sleep(5)"无法完成工作.

which make me think that a simple 'time.sleep(5)' doesn't do the work.

因此,我的问题是,如何与该新窗口完全加载后再进行交互?

谢谢

推荐答案

您可以尝试使用以下代码等待直到出现新窗口:

You can try to use following code to wait until new window appears:

WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))

您的代码应类似于

Button.click()

WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))

newWindow = driver.window_handles
newNewWindow = newWindow[1]
driver.switch_to.window(newNewWindow)

考虑@JimEvans的评论,请尝试以下操作:

Considering @JimEvans comment, try below:

current = driver.window_handles[0]
Button.click()

WebDriverWait(driver, 20).until(EC.number_of_windows_to_be(2))

newWindow = [window for window in driver.window_handles if window != current][0]
driver.switch_to.window(newWindow)

这篇关于Python 3.5-Selenium-如何处理新窗口并等待其完全加载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆