我正在开发一个 Web 应用程序,其中单击某个链接会出现另一个弹出窗口.弹出窗口不是警报,而是一个包含各种字段的表单,用户可以输入并单击下一步".
I am working on a web application, in which clicking on some link another popup windows appears. The pop windows is not an alert but its a form with various fields to be entered by user and click "Next".
如何使用 selenium 处理/自动化这个弹出窗口.
How can I handle/automate this popup windows using selenium.
总结:-
切换到弹出窗口具有挑战性,至少有两个不同的原因:
Switching to a popup is challenging for at least two separate reasons:
driver.switch_to.window(window_handle)
,这样才能在弹窗中找到元素,和弹出窗口关闭后,您可以在主窗口中找到元素.driver.switch_to.window(window_handle)
both when the popup appears, so that you can find elements in the popup window, and after the popup is closed, so that you can find elements back in the main window.这里有一些代码可以在执行您请求的序列时解决这些问题.我省略了 import
语句,并且使用了我希望显而易见的变量名.另外,请注意,我喜欢在我的代码中使用 find_element(s)_by_xpath
;随意使用其他 find_element(s)_by
方法:
Here's some code that addresses those issues while carrying out your requested sequence. I'm leaving out the import
statements, and I'm using variable names that I hope are obvious. Also, note that I like to use find_element(s)_by_xpath
in my code; feel free to use other find_element(s)_by
methods:
main_window_handle = None
while not main_window_handle:
main_window_handle = driver.current_window_handle
driver.find_element_by_xpath(u'//a[text()="click here"]').click()
signin_window_handle = None
while not signin_window_handle:
for handle in driver.window_handles:
if handle != main_window_handle:
signin_window_handle = handle
break
driver.switch_to.window(signin_window_handle)
driver.find_element_by_xpath(u'//input[@id="id_1"]').send_keys(user_text_1)
driver.find_element_by_xpath(u'//input[@value="OK"]').click()
driver.find_element_by_xpath(u'//input[@id="id_2"]').send_keys(user_text_2)
driver.find_element_by_xpath(u'//input[@value="OK"]').click()
driver.switch_to.window(main_window_handle) #or driver.switch_to_default_content()
如果有人(可能是我)需要在示例中添加更多内容或提供其他信息以使其更清晰,请告诉我.
Please let me know if someone (maybe me) needs to add more to the example, or provide other info, to make it more clear.
这篇关于用于处理弹出浏览器窗口的 Python webdriver 不是警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!