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