python wait_window_Python. Selenium. How to wait for new window opens?

问题

I have a button with twitter, and after click new window opens, but before opening there is a timout in few seconds, so is there a way to wait for it? I mait in a bad way for now...

Ui.click_el(link.W9FormNodes.TWITTER_BUTTON)

# Wait for new window and switch to it

time.sleep(3)

aw = driver.window_handles

driver.switch_to_window(aw[1])

So I need something better, that will wait only that amount of seconds that needs.

I think I solve it in this way. But maybe someone will have comments how to do it better.

aw = Ui.click_and_wait_for_window(link.W9FormNodes.TWITTER_BUTTON)

driver.switch_to_window(aw[1])

And here is a method that click on button and wait for new window:

def click_and_wait_for_window(self, node):

current_value = old_value = self.driver.window_handles

self.click_el(node)

while len(current_value) == len(old_value):

time.sleep(0.05)

current_value = self.driver.window_handles

return current_value

回答1:

As Surya mentioned, WebDriverWait would be the way to wait for a change. You could have a context manager like this that only implements the wait logic and then use it for any kind of operation you care about:

@contextmanager

def wait_for_new_window(driver, timeout=10):

handles_before = driver.window_handles

yield

WebDriverWait(driver, timeout).until(

lambda driver: len(handles_before) != len(driver.window_handles))

Here's a full working example:

from selenium import webdriver

from selenium.webdriver.support.ui import WebDriverWait

from contextlib import contextmanager

@contextmanager

def wait_for_new_window(driver, timeout=10):

handles_before = driver.window_handles

yield

WebDriverWait(driver, timeout).until(

lambda driver: len(handles_before) != len(driver.window_handles))

driver = webdriver.Chrome()

driver.get("http://www.google.com")

with wait_for_new_window(driver):

driver.execute_script("""

window.open("http://www.google.com", "_blank");

""")

with wait_for_new_window(driver, 2):

pass # This will obviously hit the timeout.

driver.quit()

回答2:

Yes; your implementation looks fine. Only thing is you need to set the timeout, otherwise it will wait for ever, if new window doesn't open.

You can combine with WebDriverWait(driver, 10).until.. to set the timeout.

Hope this helps.

来源:https://stackoverflow.com/questions/26641779/python-selenium-how-to-wait-for-new-window-opens

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值