Quick build of selenium test framework (ui automated test)

1. Introduction

Selenium is currently the mainstream web automation testing framework; it supports multiple programming languages Java, python, go, js, etc.; selenium provides a series of APIs for us to use, so we need to click a certain button on the page during web testing, then we only need to You need to get the page, then find the corresponding button according to the id or name, and then perform the click operation to complete the click action. Although it is easy to reproduce the test point, there will be a lot of repetitive work when doing the regression test, so it can be automated. We only need to run the relevant script every time we do the regression test. Selenium2: Use the Selenium automated testing framework, mainly using the Selenium Webdriver module, which can simulate and provide browsers, page element positioning, element operations, mouse and keyboard and other related operations and methods;

UI automation testing is mainly used in test scenarios such as regression testing, compatibility testing, and smoke testing; it is suitable for projects with stable requirements, long project cycles, and reusable test scripts.

Selenium installation and configuration

Browser: Google chrome (recommended), Firefox, IE, etc.

Driver: chromedriver.exe (Google) Address: ChromeDriver – WebDriver for Chrome – Downloads

Install the selenium package: pip install selenium -U, -U means installed and updated

Download the chromedriver.exe corresponding to the browser version, otherwise it may report an error that the driver cannot be found; put the driver package in the root directory of python

WebDriver schematic diagram: WebDriver is an HTTP-based protocol that provides a series of interfaces for discovering and controlling DOM elements in Web documents, and can operate browsers to do almost anything. In general, it is python to write code and control the browser through webdriver.

3. Script example

from selenium import webdriver</code><code>import time</code>
<code>#Open browser</code><code>driver = webdriver.Chrome()</code><code>#Browser maximize</code><code>driver.maximize_window()</code><code># Open baidu</code><code>driver.get("http://www.baidu.com")</code><code>#Print browser address</code><code>print (driver.current_url)</code><code>#Print page title</code><code>print(driver.title)</code><code>#Pause for a while, 3 seconds</code><code> time.sleep(3)</code><code>#Close the current window</code><code>driver.close()</code><code>#Close the entire browser and close the driver chromedriver</code> <code>driver.quit()

Unittest: Python’s unit test framework module, under which specific business test case scripts are written, and this framework can also organize the execution of test case sets and recovery of test scenarios

The time module of the standard library mainly provides operations related to time, the os.path module mainly provides operations related to file paths, the logging module mainly provides settings related to logs, and the smtplib module is mainly responsible for sending emails, etc.

Third-party module library: the HTMLTestRunner module is mainly used to generate visual test reports in HTML format, the xlrd module is a module for reading excel file data, and the xlwt module is a module for writing data to an excel file

Fourth, element positioning

During the test, the browser clicks F12 to open the console, and you can see all the buttons, input boxes and other id attributes of the page; activate the element selector; click the corresponding button and input box, and you can see the corresponding information on the console; Locate the element according to the id attribute; call the method provided by the driver to locate.

id location: driver.find_element_by_id(‘id’)

#Open Baidu, enter software test, click Baidu</code><code>driver.find_element_by_id('kw').send_keys('software test')</code><code>driver. find_element_by_id('su').click()

name location: el = driver.find_element_by_name(‘name’)

#Enter selenium automation, click on Baidu</code><code>driver.find_element_by_name('wd').send_keys('selenium automation')</code><code>#Baidu button no Provide name</code><code>driver.find_element_by_id('su').click()

Class positioning: el = driver.find_element_by_class_name(‘bt_class’)

tagName positioning: el = driver.find_element_by_tag_name(tagName)

xpath positioning (absolute path positioning): el = driver.find_element_by_xpath(xpath)

css positioning: el = driver.find_element_by_css_selector(css)

link_text positioning (according to its hyperlink positioning): el = driver.find_element_by_link_text(linkText)

partial_link_text locate(): el = driver.find_element_by_partial_link_text(linkPartText)

Get the url of the current page: driver.current_url

Get the text value of an element: driver.find_element_by_id(“iptUsername”).text

Maximize the browser window: driver.maximize_window()

View browser name: driver.name

Open the webpage: driver.get(“www.baidu.com”)

Open browser: driver = webdriver.Chrome()

Close the window: driver.close()

5. Element operation

Element assignment: el=driver.find_element_by_id(“iptUsername”).send_keys(‘admin’)

Empty element value el.clear()

Get element text: el.text

Get the value of the specified attribute of the element: get_attribute(obj)

Upload file: Find the button with type=file, click the button, and change the text of the button to the image name;

driver.find_element_by_css_selector(‘[type=”file”]’).click();

driver.find_element_by_css_selector(‘[type=”file”]’).send_keys(‘helloword.jpg’);

6. Execute JavaScript operations

When webdriver encounters an operation that cannot be completed, javascript can be used to complete it. webdriver provides the execute_script() interface to call js code. Method: execute_script(script, *args); Executing JavaScript code is a very powerful function, which can realize all functions of WebElement interface, and even more functions. For example, in the web performance test, the Web API interface window.performance can be called to test the web performance.

#Open the Baidu page and change Baidu to test </code><code>driver.get("http://www.baidu.com")</code><code>driver.execute_script( 'document.getElementById("su").value = "test"')

Seven, window switching

Browser window switching:

For example, if a browser opens multiple windows, it needs to jump from one window to another for automated testing. You have to go to another page to find the element. The principle is: each open window has a unique identifier, called a handle; window switching can be achieved through different handles.

# Current window url address: </code><code>print(driver.current_url)</code>
<code>#Pause for a while, 10 seconds</code><code>time.sleep(10)</code>
<code># Print all window handles</code><code>windows = driver.window_handles</code><code>print(windows,'\\
')</code>

<code>#Switch to the last window</code><code>driver.switch_to.window(windows[-1])</code><code>#Print url, check if it is the last window; or according to the web page Name verification</code><code>print(driver.current_url)</code>
<code>print('\\
\\
')</code><code>time.sleep(3)</code>
<code>#Switch to the second window</code><code>#Get the current window first</code><code>current_window = driver.current_window_handle</code>
<code># Get the index of the second window (from the current window index + 1)</code><code>next_window_index = windows.index(current_window) + 1</code>
<code># Switch to the second window</code><code>driver.switch_to.window(windows[next_window_index])</code><code>print(driver.current_url)

iframe toggle:

It also causes the element not to be found if the element is contained within an iframe! For example, the code: the input box with the id of kw will not be found; use driver.find_element_by_id(‘kw’) to run out of an exception that cannot be found. ?

<iframe src="frame.html" id="myframe" name="myframe"></code><code> <input id="kw" / ></code><code> </iframe>

Selenium provides the switch_to.frame() method for frame switching. This method receives id, name, index, and selenium’s WebElement object for switching. For example, in the above code, if you want to switch to an iframe, you can use the following Code:?

from selenium import webdriver</code>
<code>driver = webdriver.Chrome()</code><code># Switch iframe by id</code><code>driver.switch_to.frame('myframe') </code><code># pass name switch iframe</code><code># driver.switch_to.frame('myframe') </code><code># switch iframe by index, 0 represents the first one</code><code># driver .switch_to.frame(0) </code><code># Switch iframe through WebElement object</code><code># driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

After operating the elements in the frame, it is often necessary to switch back to the main interface for other operations. The method of switching back to the main page is as follows:

driver.switch_to.default_content()

If a frame is nested within a frame, it needs to be switched layer by layer. There are multiple frames, need to go back to the previous level; use the parent frame:

driver.switch_to.parent_frame()

alert pop-up switching:

The alert window is a js prompt box, not a web interface, ?

#Switch to the alert window; get the alert window</code><code>alert= driver.switch_to_alert</code><code>#Get the text content of the alert</code><code>print(alert.text) </code><code>#Click OK to close the bullet box</code><code>alert.accept()</code><code>#Click to cancel and close the spring</code><code>alert.dismiss( )

Eight, mouse operation

Selenium mouse events (click/double-click/right-click/drag) are explained in detail, selenium mouse events use ActionChains. Relevant modules need to be imported.

from selenium.webdriver.common.action_chains import ActionChains

If you find the Baidu click button, move to this position; ?

from selenium.webdriver.common.action_chains import ActionChains</code><code>from selenium import webdriver</code>
<code>chr_driver = webdriver.Chrome()</code><code>chr_driver.maximize_window()</code><code>chr_driver.get("https://www.baidu.com/")</code code>
<code>ele = chr_driver.find_element_by_id('su')</code><code># instantiate, hover, click, you can call multiple methods continuously, because all the returned objects are self</code><code>ActionChains(chr_driver).move_to_element(ele).pause(0.5).click(ele).perform()

Common methods of ActionChains: ?

#Click the left mouse button</code><code>click(on_element=None) </code><code>#Click the left mouse button without releasing</code><code>click_and_hold(on_element=None )</code><code>#Click the right mouse button</code><code>context_click(on_element=None) </code><code>#Double click the left mouse button</code><code>double_click(on_element=None) </code><code>#Drag to an element and release</code><code>drag_and_drop(source, target) </code><code>#Drag to a certain coordinate and release</code><code>drag_and_drop_by_offset(source, xoffset, yoffset) </code><code>#Press a key on a keyboard</code><code>key_down(value, element=None) </code><code> #Release a key</code><code>key_up(value, element=None) </code><code>#mouse moves to an element, hovers</code><code>move_to_element(to_element)</code><code>move_to_element(to_element)</code><code> code><code>#Execute all actions in the chain</code><code>perform()

9. Drag and drop

Such as: open Baidu map drag and drop, verification code verification drag action

from selenium.webdriver.common.action_chains import ActionChains</code>
<code>#Open browser</code><code>driver = webdriver.Chrome()</code><code>#Browser maximize</code><code>driver.maximize_window()</code><code>#Open Baidu map</code><code>driver.get('https://map.baidu.com/@12697919.69,2560977.31,12z')</code>
<code>#Location Map</code><code>mask = driver.find_element_by_id('mask')</code>
<code>#action</code><code>ac = ActionChains(driver)</code><code>ac.move_to_element(mask).click_and_hold().move_by_offset(50,50).release().perform() 

10. Page waiting

Forced waiting: time.sleep()

Implicit wait: driver.implicitly_wait(t), implicitly waits for the page to be loaded within the specified time t, if the loading time is less than t, the remaining time will not wait; if the loading is not completed within the time t, an error will be reported . Scope of action: global

Explicit wait: WebDriverWait(driver, timeout, poll_frequency).until(element)

Import: from selenium.webdriver.support.ui import WebDriverWait

Explicit waiting can be regarded as a special implicit waiting. It waits for the specified element to be loaded within the specified time t. If the loading completion time is less than t, the remaining time will not wait. If the loading is not completed within t time, then error.

Method: WebDriverWait(driver, timeout, poll_frequency)

driver: indicates the browser object, timeout: indicates the timeout period, poll_frequency: the scanning interval is generally 0.5 seconds, and the page is scanned once.

element: specifies the loaded element

Eleven, screenshot

driver.save_screenshot(file): file, the path and name of the image saved locally;

Such as: driver.save_screenshot(‘./Homepage.jpg’)

driver. get_screenshot_as_file(file)

Usage scenario: Usually the assertion fails, save the screenshot when there is an error, and restore the scene conveniently.

12. Call js code

excute_script(js)

Such as: set value for read-only elements; set date; ?

js = 'document.getElementById("date").value = 2022-05-27'</code><code>driver.execute_script(js)

Thirteen, warning box processing

Three types of alert boxes:

alert: only OK button;

confirm: There are OK and Cancel buttons

prompt: You can enter content;

Method:

swtch_to.alert.text: Get the text information in the alert box

swtch_to.alert.accept(): Click OK in the alert box

swtch_to.alert.dismiss(): Click Cancel in the alert box

swtch_to.alert.send_keys(value): Enter content in the alert box?

#Print the text information in the warning box</code><code>print(swtch_to.alert.text)</code><code>#Click OK in the warning box</code><code>driver.swtch_to .alert.accept()</code><code>#Click to cancel in the warning box</code><code>driver.swtch_to.alert.dismiss()</code><code>#Input content in the warning box 100 blocks</code><code>driver.swtch_to.alert.send_keys('100 blocks')

Fourteen, drop-down box

Import module: from selenium.webdriver.support.select import select

Suppose the drop-down box is s; select the option in the drop-down box Select(s).Method()

Method:

options : returns all options in the drop-down box

select_by_index(): select by index

select_by_value(): Select by the value attribute value of the option

select_by_visible_text(): select by the text value of the option

?

#Locate the drop-down box, the content is the province</code><code>s = driver.find_element_by_id('province')</code><code>#Get all the options in the drop-down box</code> <code>opt = Select(s).options</code><code>#Select by index; if it is selected by value, the html code should be written with value attribute</code><code>Select(s).select_by_index( -1)

Fifteen, ActionChains action chain

ActionChains can help simulate mouse actions; such as single click, double click, right mouse click, drag and drop, etc. Using the actionchains object method, action events are stored in the actionchains object queue. When you use perform(), events are performed sequentially.

There are two calling methods: #chain writing

ActionChains(driver).click(click_btn).double_click(doubleclick_btn).perform()</code>
<code>#Step by step</code><code>ActionChains(driver).click(click_btn)</code><code>ActionChains.double_click(doubleclick_btn)</code><code>ActionChains.perform()</code pre>
<p>Common methods of ActionChains:</p>
<pre>click(on_element=None) - click the left mouse button</code>
<code>click_and_hold(on_element=None) --Click the left mouse button without releasing it</code>
<code>context_click(on_element=None) - click the right mouse button</code>
<code>double_click(on_element=None) - double click the left mouse button</code>
<code>drag_and_drop(source, target) - drag to an element and release</code>
<code>drag_and_drop_by_offset(source, xoffset, yoffset) --drag to a certain coordinate and release</code>
<code>key_down(value, element=None) - press a key on the keyboard</code>
<code>key_up(value, element=None) - release a key</code>
<code>move_by_offset(xoffset, yoffset) - the mouse moves from the current position to a certain coordinate</code>
<code>move_to_element(to_element) - move the mouse to an element</code>
<code>move_to_element_with_offset(to_element, xoffset, yoffset)--Move to the distance from an element (upper left corner coordinates)</code>
<code>perform() - execute all actions in the chain</code>
<code>release(on_element=None) - release the left mouse button at an element position</code>
<code>send_keys(*keys_to_send) - send a key to the currently focused element</code>
<code>send_keys_to_element(element, *keys_to_send) - send a key to the specified element

Sixteen, table processing

The table table code is as follows: ?

<table border="1"></code><code> <tr></code><code> <td>row 1, cell 1</td></code><code> <td>row 1, cell 2</td></code><code> </tr></code><code> <tr></code><code> <td>row 2, cell 1</td></code><code> <td>row 2, cell 2</td></code><code> </tr></code><code></table>

Obtain the content in the table, and obtain it layer by layer through table->tr->td?

#Get table</code><code>table = driver.find_elements_by_id('table')</code>
<code>#Get tr</code><code>tr = table.find_elements_by_tag_name('tr')</code>
<code>#Get td</code><code>td = tr[1].find_elements_by_tag_name('td')</code>
<code>#Output content</code><code>print(td[1].text)

Seventeen, production report

Connect to the database, input all test case running results into the database, and then read the database to generate test reports; such as: the total number of test cases, the number of successful cases, the number of failed cases, the number of skipped cases; the number of test cases for each module , the number of successful use cases, the number of failed use cases, and the number of skipped cases;

END