Use Selenium+python; Click a button in page A to jump to page B, page A does not close, the browser opens a B, toggle the window to locate the elements of page B

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/hhabc123456789/article/details/21862139

#-*-coding:cp936-*-
__author__ = ' Administrator '

Import Unittest,time,re
From selenium import Webdriver

Class Untitled (UnitTest. TestCase):
def setUp (self):
Self.driver = Webdriver. Chrome ()
Self.driver.implicitly_wait (10)
Self.url = "Http://www.baidu.com"

def test_untitled (self):
Driver = Self.driver
Driver.get (Self.url)
Now_handle = Driver.current_window_handle #获取当前窗口句柄
Print Now_handle #输出当前获取的窗口句柄
driver.find_element_by_id ("Kw1"). Send_keys ("Selenium")
driver.find_element_by_id ("SU1"). Click ()
Driver.find_element_by_xpath ("//*[@id = ' 1 ']/h3/a[1]"). Click ()
Time.sleep (2)
All_handles = Driver.window_handles #获取所有窗口句柄

For handle in All_handles:

If handle! = Now_handle:
Print Handle #输出待选择的窗口句柄
Driver.switch_to_window (handle)
Driver.find_element_by_xpath ("//*[@id = ' menu_projects ']/a"). Click ()
Time.sleep (5)
Driver.close () #关闭当前窗口
Time.sleep (3)
Print Now_handle #输出主窗口句柄
Driver.switch_to_window (Now_handle) #返回主窗口
Time.sleep (2)
driver.find_element_by_id ("kw"). Clear ()
driver.find_element_by_id ("kw"). Send_keys ("abc")
driver.find_element_by_id ("su"). Click ()

Time.sleep (10)

def tearDown (self):
Self.driver.quit ()
#pass


if __name__ = = "__main__":
Unittest.main ()

In Python 2.7 using Google Chrome, the output handle results are:

Cdwindow-6a91cfa2-f107-47fb-9cee-06e6e4015fe0
cdwindow-c22573f7-eafa-41ff-911b-b63aa2d9246f
Cdwindow-6a91cfa2-f107-47fb-9cee-06e6e4015fe0

Report:

You can also use Driver.switch_to_window (Driver.window_handles[-1]) to get the currently open window

Use Selenium+python; Click a button on page A to jump to page B, page A is not closed, the browser opens a B, the toggle window locates the element of page B

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.