Python 3.5 - Selenium - 如何处理新窗口并等待它完全加载?

标签 python selenium selenium-webdriver browser webdriver

我正在做浏览器自动化,我在某个时候被阻止了:有一刻,我要求浏览器点击一个按钮,这又会打开一个新窗口。但有时因特网太慢,所以这个新窗口需要时间来加载。我想知道如何让 Selenium 等待这个新窗口完全加载。

这是我的代码:

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]

IndexError: list index out of range

这让我觉得简单的“time.sleep(5)”无法完成工作。

那么,我的问题是,如何才能等到这个新窗口完全加载后再与之交互?

谢谢

最佳答案

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

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 的评论,请尝试以下操作:

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 - 如何处理新窗口并等待它完全加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41571217/

相关文章:

python - 填充 Pandas 数据框中缺失的中间值

python - 在 Python 上将数据写入 CSV 会将所有数据写入第一列

selenium.common.exceptions.NoSuchElementException 在 python 3.7 中使用 selenium

Python Selenium 屏幕抓取

python - 将 SSL 证书添加到 Selenium

Python Celery 自动缩放 Kubernetes

python - Google App Engine 中命名键或 "pre-generated"键的性能成本是多少?

linux - Selenium 测试用例在 Firefox 中有效,但在 Chrome 中无效 - Headless Setup

java - WebDriver + TestNG Gmail 一个奇怪的错误

python - xpath表达式 "html/body/div/text()[1]"的结果是: [object Text].它应该是使用Selenium打印元素文本的元素错误