As we all know, The basic framework of Web-based testing needs Selenium as the main support. Here we introduce the Python-based Selenium, the core of Web testing

A brief introduction

Selenium is a common framework for testing Web application user interfaces (UIs). It is a powerful tool for running end-to-end functional tests. You can write tests in more than one programming language, and Selenium can execute these tests in one or more browsers.

Two, environmental installation

  1. Install Python, this… Ignore python2.7.

  2. PIP install Selenium ==2.53.6, you get the idea.

  3. Install the browser driver package, it is recommended to use Chrome chromedriver. Exe, the corresponding Chrome version must be right, or it will not run, where to install it? Put it wherever you want, but usually in python’s root directory. Download address: chromedriver.storage.googleapis.com/index.html

  4. Install PyCharm 2.7 or so, this brainless install ~ then you can customize the UI and coding style, this… ignore

Three, the knife test

1. Control the browser

#coding=utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.baidu.com")
driver.maximize_window() # Maximize browser display
driver.set_window_size(480, 800) # set browser width 480, height 800 display"
 driver.back() # back
driver.forward() # forward
 driver.close() # close chrome
driver.quit() # exit chromeIf software testing, interface testing, automated testing, performance testing, LR script development, interview experience exchange. If you are interested, you can go to 175317069. There will be free information links in the group from time to time, which are collected and sorted out from various technical websites. If you have good learning materials, you can send them to me privately.Copy the code

2. Locate the object

  • Location by ID: find_element_by_id()

  • Locate by name: find_element_by_name()

  • Location by class: find_element_by_class_name()

  • Location by tag: find_element_by_tag_name()

  • Location via link: find_element_by_link_text()

  • Locate by partial_link: find_element_by_partial_link_text()

  • Location by xpath: find_element_by_xpath()

  • Location via CSS: find_element_by_css_selector()

The above positioning is a routine operation, which should be basically enough, but sometimes there will be some weird positioning failure or locating the failure of the click. At this time, if you use JS to directly execute the event, the next unconventional operation will be introduced:

  • Id location: document.getelementById ()

  • The name positioning: the document. The getElementsByName ()

  • The tag positioning: the document. The getElementsByTagName ()

  • Class location: document. GetElementsByClassName ()

  • CSS positioning: document. QuerySelectorAll ()

   search_js = "document.getElementsByName('wd')[0].value='selenium';"# select selenium by name and assign it to selenium.
   search_js2 = "document.querySelectorAll('.s_ipt')[0].value='selenium';"# CSS location, then assign "Selenium"
   button_js = "document.getElementById('su').click();"Locate by ID, and then click
   button_js2 = "document.getElementsByClassName('s_btn')[0].click()"Execute_script (search_js2)# Execute, execute_script(script, *args)
    
Copy the code

Above several positioning is can upgrade again, can use jQuery positioning a wave, here can see the summary before the JQ selector of mind mapping knowledge (www.cnblogs.com/aoaoao/arti… JS, then ignore

3. Operate the test object

#coding=utf-8
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://passport.kuaibo.com/login/")
driver.find_element_by_id("user_name").clear() Clear the default contents of the input box
driver.find_element_by_id("user_name").send_keys("username")
driver.find_element_by_id("user_pwd").clear()
driver.find_element_by_id("user_pwd").send_keys("password") # Enter the input box as "password"
driver.find_element_by_id("dl_an_submit").click() Submit the action via submit()
driver.find_element_by_id("dl_an_submit").submit()
size=driver.find_element_by_id("kw").size Text =driver.find_element_by_id("cp"). Text # Return the record information at the bottom of the Baidu page
# return the value of the element's attribute, which can be id, name, type, or any other attribute the element owns
attribute=driver.find_element_by_id("kw").get_attribute('type') # return whether the result of the element is visible, True or False
result=driver.find_element_by_id("kw").is_displayed()
driver.quit() # exit
Copy the code

4. Mouse and keyboard events

from selenium import webdriver # introduce the Keys package
from selenium.webdriver.common.keys import Keys # introduce ActionChains
from selenium.webdriver.common.action_chains import ActionChains
... # Mouse events # Locate the element to manipulate
right =driver.find_element_by_xpath("xx") # Right-click the located element
ActionChains(driver).context_click(right).perform() # Double-click on the located element
ActionChains(driver).double_click(right).perform() # Move the mouse over the located element
ActionChains(driver).move_to_element(right).perform() # Left mouse button down on the located element
ActionChains(driver).click_and_hold(right).perform() # Locate the original position of the element
element = driver.find_element_by_name("xxx") Locate the target location to which the element will be moved
target = driver.find_element_by_name("xxx") Move the element
ActionChains(driver).drag_and_drop(element, target).perform() Delete a value for multiple inputs
driver.find_element_by_id("kw").send_keys(Keys.BACK_SPACE) # Enter space bar + "Tutorial"
driver.find_element_by_id("kw").send_keys(Keys.SPACE)
driver.find_element_by_id("kw").send_keys(u"Tutorial") # CTRL + X cut the input field
driver.find_element_by_id("kw").send_keys(Keys.CONTROL,'x') # The rest of the keyboard is similar
Copy the code

5. Wait time


#coding=utf-8
from selenium import webdriver Import the WebDriverWait package
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC Import the time package
import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com") Use the #WebDriverWait() method to display the wait,WebDriverWait(driver, timeout duration, call frequency, ignore exceptions). Until (executable method, information returned by timeout), where EC can be called to implement the executable methodis_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).until_not(lambda x: X.f ind_element_by_id (kw). Is_displayed ())#until(method, message= "), call the driver provided by the method as an argument until the return value is not False
element.send_keys("selenium") # Add intelligent wait, hidden wait
driver.implicitly_wait(30)
driver.find_element_by_id("su").click() # Add fixed sleep time to enforce wait
time.sleep(5)
driver.quit()
Copy the code

6. Group object location and hierarchy location, er, ignored

7. Multi-window processing

#coding=utf-8
from selenium import webdriver import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com/") Get the current window
nowhandle=driver.current_window_handle Open the register new window
driver.find_element_by_name("tj_reg").click()
allhandles=driver.window_handles # loop to determine if the window is the current window
for handle in allhandles: ifhandle ! = nowhandle: driver.switch_to_window(handle)print 'now register window! '
# Switch to the mailbox registration TAB
driver.find_element_by_id("mailRegTab").click()
time.sleep(5)
driver.close() Return to the original window
driver.switch_to_window(nowhandle)
driver.find_element_by_id("kw").send_keys(u"Registration successful!")
time.sleep(3) Id, name will be automatically recognized. If not, the element can be found through the selector, and then enter the element
driver.switch_to_frame("f1")
element = driver.find_element_by_id("kw")
driver.switch_to_frame(element)
driver.quit() 
Copy the code

8. Prompt window processing

#coding=utf-8
from selenium import webdriver import time
driver = webdriver.Chrome()
driver.get("http://www.baidu.com/") # Click to open search Settings
driver.find_element_by_name("tj_setting").click()
driver.find_element_by_id("SL_1").click() # Click save Settings
driver.find_element_by_xpath("//div[@id='gxszButton']/input").click() # Get the warning information on the web page
alert=driver.switch_to_alert() Receive warning messages
alert.accept() # Cancel dialog (if one exists)
alert.dismiss() Enter a value (if any)Alert. Send_keys (" XXX ")Copy the code

9. Control the browser scroll bar, using the jQ statement suggested earlier

10. Cookie processing is mainly used to deal with verification code problems

#coding=utf-8
from selenium import webdriver import time
driver = webdriver.Chrome()
driver.get("http://www.youdao.com") Add session information to cookie name and value.
driver.add_cookie({'name':'key-aaaaaaa'.'value':'value-bbbb'}) # Iterate over the name and value information printed in cookies, as well as the information added above
for cookie in driver.get_cookies(): print "%s -> %s" % (cookie['name'], cookie['value']) ##### There are two ways to delete a cookie ##### # to delete a specific cookie
driver.delete_cookie("CookieName") Delete all cookies
driver.delete_all_cookies()
time.sleep(2)
driver.close()
Copy the code

Four, summary

If software testing, interface testing, automated testing, performance testing, LR script development, interview experience exchange. If you are interested, you can go to 175317069. There will be free information links in the group from time to time, which are collected and sorted out from various technical websites. If you have good learning materials, you can send them to me privately.

After familiarizing yourself with the basic operations of selenium’s common APIS, it is time to design actual test cases. A good automated test case meets the following five requirements:

1, a script is a complete scenario, from the user login operation to the user exit the system to close the browser.

2, a script script only verify one function point, do not try to log in the system after all functions are verified and then log out of the system

3, is to do only function logic validation as far as possible, don’t think too much of reverse logic, reverse logic of many (such as hand Mistyped no. There are many kinds of situations), validation on the one hand, is more complex, you need to write a lot of scripts, automated script itself is weak on the other hand, a lot of abnormal logical validation of ability is not strong. (We try to follow the user’s normal usage principles to write scripts)

4. Scripts should not be associated with each other, which means that each script written is independent and cannot depend on or affect other scripts.

5. If the data is modified, restore the data. Verify only verification points throughout the script, not every step of the script.

Finally, we cooperate with unittest or testNG unittest framework to realize hierarchical, data-driven, assertion, screenshot, log and other all-round functions, and carry out automated testing with ease.