SELENIUM2 Python Automated Test Study notes (iii)

Source: Internet
Author: User
Tags tesseract ocr

4.9 Multi-form switching

In the Web application often encounter the application of frame nested page, webdriver can only identify elements on one page at a time, for the elements on a frame nested page, the direct positioning is not located, then need to Switch_to_frame () method to switch the currently positioned body into a frame. Frame.htm:frame.htm, direct positioning Baidu input box will be reported to find the error of the element. Then you can use Switch_to_frame () to find the <iframe> tag in frame.html, and then locate the Baidu input box. Switch_to_frame () can be switched directly from the form's ID or the Name property by default. If you have completed the operation on the current form, you can return to the previous layer form by using the Switch_to_default_content () method, instead of specifying the return of a form, which corresponds to its closest switch_to_frame () method by default.

frame.py

#coding =utf-8

From Selenium Importwebdriver

Import Time,os

Driver=webdriver. Chrome ()

File_path= "file:///" +os.path.abspath ("frame.htm")

Driver.get (File_path)

Driver.switch_to_frame ("if")

driver.find_element_by_id ("kw"). Send_keys ("Selenium")

driver.find_element_by_id ("su"). Click ()

Time.sleep (3)

Driver.switch_to_default_content ()

Time.sleep (3)

Driver.close ()

4.1 Multi-Window switching

Sometimes you need to switch between different windows to manipulate the elements on different windows. Webdriver provides the Switch_to_window () method to switch to any window. window.py

#conding =utf-8

From selenium import Webdriver

Driver=webdriver. Chrome ()

Driver.implicitly_wait (10)

Driver.get ("http://www.baidu.com")

Search_windows=driver.current_window_handle

Driver.find_element_by_link_text (U ' login '). Click ()

Driver.find_element_by_link_text (U ' Register Now '). Click ()

All_handles=driver.window_handles

#进入注册窗口

For handle in All_handles:

If handle!=sreach_windows:

Driver.switch_to_window (handle)

print ' Now registerwindow! '

Driver.find_element_by_name ("Account"). Send_keys (' username ')

Driver.find_element_by_name (' password '). Send_keys (' password ')

#进入搜索窗口

For handle in All_handles:

If handle ==sreach_windows:

Driver.switch_to_window (handle)

print ' Now sreachwindow! '

driver.find_element_by_id (' tangram__psp_2__closebtn '). Click ()

driver.find_element_by_id ("kw"). Send_keys ("Selenium")

driver.find_element_by_id ("su"). Click ()

Time.sleep (5)

Driver.close ()

The whole process of the script: first open Baidu home, through Current_window_handle get the current window handle, and to the variable sreach_handle. Then open the login popup and click "Register Now" in the login window to open the new registration window. Assigns a value to the variable all_handles by window_handles the handle to the currently open window.

The first loop iterates through the all_handles, and if handle is not equal to Sreach_handle, then it must be the registration window, because the script executes only the two windows that are open. So, switch to the registration page via Switch_to_window () to register the operation. The second loop is similar, but this time judge if handle equals sreach_handle, then switch to Baidu Search page, close the Login pop-up window before opening, and then the rows search operation.

In this example, all new methods are used:

Current_window_handle getting the current window handle

Window_handles returns the handle of all windows to the current session

Switch_to_window ()

Used to switch to the appropriate window, similar to the Switch_to_frame () in the previous section, which is used for switching between different windows, which is used for switching between different forms.

4.11 Warning Box handling

It is easy to deal with the alert, confirm, and prompt generated by JavaScript in Webdriver. The specific approach is to use the Switch_to_alert () method to navigate to Alert/confirm/prompt. Then use Text/accept/dismiss/send_keys to do the work as needed.

L Text returns the text information in the alert/confirm/prompt.

L Accept click the Confirm button.

L Dismiss click the Cancel button, if any.

L Send_keys Input value, this alert\confirm no dialog box can not be used, otherwise it will be an error.

The popup cannot be positioned by the front-end tool and can receive the pop-up through the Switch_to_alert () method.

alert.py

#coding =utf-8

From selenium import Webdriver

From Selenium.webdriver.common.action_chains import Actionchains

Import time

Driver=webdriver. Chrome ()

Driver.implicitly_wait (10)

Driver.get ("http://www.baidu.com")

#mouse Stop Set link

Link=driver.find_element_by_name ("Tj_settingicon")

Actionchains (Driver). move_to_element (link). Perform ()

#open Search Setting

Driver.find_element_by_link_text (U ' Search Settings '). Click ()

#save Set

Driver.find_element_by_link_text (U ' Save Settings '). Click ()

#recieve Pop_window

Driver.switch_to_alert (). Accept ()

Time.sleep (5)

Driver.close ()

The Actionchains class provides the use of move_to_element () mouse hover, hover over the "search" link and pop-up the drop-down menu. Click the "Search Settings" button in the menu. Click "Save Settings" pop-up warning box to complete the settings. The Switch_to_alert () method gets the warning box on the current page, and accept () accepts the warning box.

4.12 Uploading Files

For the Web page upload function, click the Upload button to open the Local Windows window, select a local file from the window to upload, then webdriver for Windows control is powerless.

There are generally several ways to upload a Web page.

Normal upload : normal upload is the path of the local file as a value in the input tag, submitted by the form form when the value is submitted to the server.

plugin upload : generally refers to the upload function or plugin based on technologies such as Flash and JavaScript or Ajax.

4.12.1 Send_keys () implement upload

Uploads are implemented via the input tag, and a local file path is passed through Send_keys () to simulate the upload function. Upfile.htm:upfile.htm

upfile.py

#coding =utf-8

From Seleniumimport Webdriver

Import Os,time

Driver=webdriver. Chrome ()

#open upfilefuntion Page

File_path= "file:///" +os.path.abspath ("upfile.htm")

Driver.get (File_path)

#locate theupload button and add File

Driver.find_element_by_name ("file"). Send_keys ("D:\\session_help.txt")

Time.sleep (10)

Driver.close ()

By uploading this method, you bypass the steps to manipulate windows controls. If you can find the uploaded input tag, then basically you can use the Send_keys () method to enter a file address to achieve the upload.

4.12.2 AutoIt Implementation Upload

Autolt is a free software that uses a similar basic scripting language and is designed for automated operations in the Windows GUI. It uses analog keyboard keys, mouse Movement and window/control combinations to automate tasks.

Official website: https://www.autoitscript.com/site/

AutoIt Windows info is used to help us identify Windows control information.

Compile Script To.exe is used to generate AutoIt exe execution files.

Run script is used to execute the AutoIt script.

The SciTE script Editor is used to write AutoIt scripts.

Following the operation upload.html upload pop-up window as an example to explain the autoit implementation of the upload process.

1, first open the AutoIt Windows Info tool, mouse click on Finder tools, the mouse will become a small fan-shaped icon, hold down the left mouse button to drag the control to be recognized.

4.14, 4.15, through AutoIt Windowsinfo obtain the following information.

The title of the window is "Select Files to load" and the heading is "#32770".

The file name input box has the class "Edit" and Instance "1", so Classnamenn is "Edit1".

The Open button's class is "button" and Instance is "1", so Classnamenn is "Button1".

2. Open the Scitescript editor and write the script according to the control information that Autoitwindows info recognizes.

The Controlfocus () method is used to identify window windows. Winwait () Sets 10 seconds to wait for the display of the window, similar in usage to the implicitly_wait () provided by Webdriver. Controlsettext () is used to enter the path to the local file in the file name input box. The sleep () method here is the same as the sleep () method provided by the time module in Python, but it is in milliseconds and Sleep (2000) represents a fixed sleep of 2000 milliseconds. Controlclick () is used to click the "Open" button in the Upload window.

AutoIt's script has been written, and you can run a script from the menu bar "Tools" and "Go" (or press keyboard F5)! Note the Upload window is currently open at run time.

3, the script runs normally, save it as UPFILE.AU3, where the saved script can be opened by the Run Script tool, but we want this script to be called by the Python program, then we need to generate an EXE program. Open the Compile Script to.exe tool and generate it as an EXE executable file. 4.16,

Click "Browse" to select the Upfile.au3 file and click the "Convert" button to generate it as a upfile.exe program.

4, the following is through the automated test script call Upfile.exe program implementation upload. upfile_by_autoit.py:

#coding =utf-8

From Seleniumimport Webdriver

Import Os,time

Driver=webdriver. Chrome ()

#open theupload funtion Page

File_path= "file:///" +os.path.abspath ("upfile.htm")

Driver.get (File_path)

Time.sleep (10)

#click TheOpen Upload Window

Driver.find_element_by_name ("File"). Click ()

#callupfile. exe programe

Os.system ("C:\\users\\ewang\\desktop\\python_selenium2\\upflie.exe")

Driver.close ()

4.13 Operating Cookies

Sometimes we need to verify that there is a cookie in the browser because testing based on a real cookie cannot be done with white-box and integration testing. Webdriver provides a way to manipulate cookies to read, add, and delete cookie information.

Webdriver How to manipulate cookies are:

get_cookies () Get all cookie information

get_cookie (name) returns a specific name value with cookie information

add_cookie (cookie_dict) to add a cookie, the name and value must be

delete_cookie (name) delete specific (partial) cookie information

delete_all_cookies () Delete all cookie information

The following is a get_cookies () to obtain cookie information for the current browser. cookie.py

#coding =utf-8

From Seleniumimport Webdriver

Import time

Driver=webdriver. Chrome ()

Driver.get ("http://www.youdao.com")

Cookie=driver.get_cookies ()

Ck_nu=0

For CK Incookie:

Ck_nu=ck_nu+1

Print "The%d cookie: \ t%r \ n"% (CK_NU,CK)

Driver.close ()

By printing the results can be seen that the cookie is stored in the form of a dictionary, know the form of cookie storage, then we can follow this form to the browser to write cookie information. add_cookie.py

#coding =utf-8

From selenium import Webdriver

Import time

Driver=webdriver. Chrome ()

Driver.get ("http://www.youdao.com")

Driver.add_cookie ({' name ': ' Key-enlong ', ' value ': ' Value-loveyou '})

For CK in Driver.get_cookies ():

Print "%s,%s"% (ck[' name '], ck[' value ')

Driver.close ()

Then under what circumstances will the operation of the cookie be used? For example, a developer develops a feature that, when the user logs in, writes the user's username to the browser cookie, the specified key is "username", then we can find Useranme, print Vlaue through Get_cookies (), If the username is not found or the corresponding value is null, then the cookie for saving the browser is problematic.

The use of Delete_cookie () and Delete_all_cookies () is also simple, the former is deleted by the name value to a specific cookie, which directly deletes all cookies () information in the browser.

4.14 Calling JavaScript

Webdriver cannot manipulate local windows controls, but it is not always possible to manipulate the controls for the browser. For example, the scroll bar on the browser, although Webdriver provides the operation of the browser's forward and backward buttons, but the scroll bar does not provide a corresponding method. Webdriver provides the Execute_script () method to execute JavaScript.

There are two scenarios in which the scroll bar is generally manipulated:

L READ the legal provisions at the time of registration to determine whether the user is reading the standard of completion: whether the scroll bar is pulled down at the bottom.

L operation of the page is not in the visual range, unable to perform the operation, you need to drag the scroll bar.

Code to identify the position of the scroll bar:

<bodyonload= "Document.body.scrolltop=0" >

<bodyonload= "document.body.scrolltop=100000" >

Document.body.scrollTop:scrollTop Sets or gets the distance between the scroll bar and the top. If you want the scroll bar to be at the top, you can set the value of ScrollTop to 0, if you want the scroll bar to be at the bottom, you can set the value large enough to the height of the window. Html. PY:

#coding =utf-8

From Seleniumimport Webdriver

Import time

Driver=webdriver. Chrome ()

Driver.get ("http://www.baidu.com")

driver.find_element_by_id ("kw"). Send_keys ("Selenium")

driver.find_element_by_id ("su"). Click ()

Time.sleep (3)

Js= "varq=document.documentelement.scrolltop=10000"

Driver.execute_script (JS)

Time.sleep (3)

js_= "Varq=document.documentelement.scrolltop=0"

Driver.execute_script (Js_)

Time.sleep (3)

Driver.close ()

Using JavaScript code to control the scrollbar in any position, you need to change the value of scrolltop. Use the Execute_script () method to execute this JavaScript code. Of course, JavaScript works not only here, it can also manipulate elements on the page or let, or let this element be hidden.

4.15 windows

The automation script is given to the tool to execute, sometimes the error message printed is very ambiguous, if the execution of the script error will be saved to the current window, through the picture information to find the cause of the script error. Webdriver provides a function get_screenshot_as_file () to intercept the current window. screenshot.py

#coding =utf-8

From selenium import Webdriver

Driver=webdriver. Chrome ()

Driver.get ("http://www.baidu.com")

Try

driver.find_element_by_id ("Kw_22"). Send_keys ("Selenium")

driver.find_element_by_id ("su"). Click ()

Except:

Driver.get_screenshot_as_file ("D:\\baidu. JPG ")

Driver.quit ()

In this case, the id=kw_error of the Baidu input box will not locate the element, then the try will catch the exception, thus executing except, in except execution Get_screenshot_as_file () to the current window, You need to specify the save path and file name of the picture, and close the current driver. When the script runs, you can find the Baidu_error.jpg picture file by opening the D drive.

4.16 Closing the window

Quit () method: Exits the associated driver and closes all windows

Close () method: Used to close the current window

When a script opens multiple windows at execution time, it can only close one of the windows at this time, and it needs to be closed by using close ().

4.17 Processing of verification codes

1. Remove the verification code

This is the simplest way, for developers, just to comment out the code codes, if it is in the test environment, this can save the testers a lot of trouble, if the automation script is to run in the formal environment, so that the system poses a certain risk.

2. Set the Universal code

Remove the verification code is primarily a security issue, in order to deal with the security threats of online systems, you can modify the program without canceling the verification code, but the program to leave a "backdoor"---set a "Universal Verification code", as long as the user input this "Universal Verification Code", the program is considered to pass the verification, Otherwise, it is verified by the original verification method.

1. Verification Code Identification Technology

For example, the python-tesseract can be used to identify the image verification code, Python-tesseract is the optical character recognition tesseract OCR engine Python wrapper class. Ability to read any regular picture files (JPG, GIF, PNG, TIFF, etc.). However, there are many types of verification codes on the market at present, any authentication code recognition technology, the recognition rate is not 100%

2. Record cookies

Adding cookies to your browser bypasses the sign-in verification code, which is a more interesting solution. For example, we can check the "Remember password" option when we first log in to a website, and will be logged in automatically the next time you visit the website. This actually bypasses the captcha problem as well. Then this "Remember password" function is actually recorded in the browser's cookie. Webdriver to operate the browser cookie, the user name password can be written to the browser cookie via the Add_cookie () method, and the server reads the browser cookie login directly when the website is visited again.

The biggest problem in this way is how to find the key value corresponding to the user name and password from the browser's cookie, and transmit the corresponding login information. The Get_cookies () method can be used to obtain all the cookie information that is logged in and find the key for the user name and password. Of course, there is a security risk if the site does not write a cookie at all when the user name and password are logged on. Then this approach will not work.

4.18 Webdriver Principle

Webdriver is designed in accordance with the classic design of the Server-client Classic model.

Webdriver Workflow:

1. Webdriver launches the target browser and binds to the specified port. The browser instance that is launched as a remote server for Webdriver.

2. Client side sends HttpRequest to remote server listening port via Commandexcuter (Communication protocol: the Webriver Wire protocol)

3. Remote server needs to rely on native browser components (such as: IEDriverServer.exe, Chromedriver.exe) to convert native calls to the browser.

The logging module is available in Python, and the logging module provides a standard information output interface for running applications. It provides a definition of the Basicconfig () method for basic information. Turn on the Debug module. You can capture the client-server interaction information. The debug mode turned on by Basicconfig () only captures the POST request sent by the client to the server, and cannot obtain the response returned by the server. test.py

#coding =utf-8

From selenium import Webdriver

Import logging

Logging.basicconfig (level=logging. DEBUG)

Diver = Webdriver. Chrome ()

Diver.get ("http://www.baidu.com")

diver.find_element_by_id ("kw"). Send_keys ("Selenium")

diver.find_element_by_id ("su"). Click ()

Diver.quit ()

SELENIUM2 Python Automated Test Study notes (iii)

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.