1. Browser
1.1 Browser Window Size location
Driver.set_window_size (self, width, height, windowhandle) sets a window to a fixed size
Driver.set_window_position (self, x, y, windowhandle) moves a window to the specified position
Driver.set_window_rect (self, x, y, width, height, windowhandle) moves a window to a fixed size to the specified position
Driver.maximize_window () window maximization
Driver.minimize_window () window minimized
From selenium import Webdriver
Driver = Webdriver. Firefox ()
Driver.get ("http://www.baidu.com")
Driver.set_window_rect (300, 300, 480, 800)
Driver.set_window_position (300, 300)
Driver.maximize_window ()
Driver.minimize_window ()
1.2 Controlling the browser's back and forth
Driver.back ()
Driver.forward ()
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
F_url = "Https://www.baidu.com"
S_url = "Https://news.baidu.com"
Driver.get (F_url)
Time.sleep (1)
Driver.get (S_url)
Time.sleep (1)
Driver.back ()
Assert F_url in Driver.current_url, "Current URL not first URL"
Print (Driver.current_url)
Time.sleep (1)
Driver.forward ()
Assert S_url in Driver.current_url, "Current URL not second URL"
Print (Driver.current_url)
Driver.close ()
1.3 Simulating browser refreshes
Driver.refresh ()
2. Element manipulation
Clear Erase Text
Send_keys (value) analog key input
Click ()
Submit () Submission form, such as the enter operation after the search box input, can be simulated by the submit () method
Size returns the dimensions of the element
Text gets the literal of the element
Get_attribute (name) Gets the property value
Is_displayed () returns whether the element is visible, Boolean type
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
F_url = "Https://www.baidu.com"
Driver.get (F_url)
driver.find_element_by_id ("kw"). Send_keys ("Hello")
Print (driver.find_element_by_id ("CP"). Text)
driver.find_element_by_id ("kw"). Clear ()
driver.find_element_by_id ("kw"). Send_keys ("Selenium")
driver.find_element_by_id ("kw"). Submit ()
Print (size)
Print (driver.find_element_by_id ("kw"). Get_attribute ("name"))
Print (driver.find_element_by_id ("kw"). Is_displayed ())
Driver.close ()
3. Mouse events
Perform () performs the behavior stored in all Actionchains
Context_click () Right-click
Double_click () Double-click
Drag_and_drop () drag
Move_to_element () mouse hover
Right-click Not implemented
From selenium import Webdriver
From selenium.webdriver.common.action_chains import actionchains
Import time
Driver = Webdriver. Firefox ()
F_url = "Https://www.baidu.com"
Driver.get (F_url)
Driver.find_element_by_link_text ("Map"). Click ()
Driver.find_element_by_xpath ("//span[@class = ' success ']"). Click ()
Nowpos = Driver.find_element_by_xpath ("//*[@class =\" normal\ "][1]")
Actionchains (Driver). Context_click (Nowpos). Perform ()
Time.sleep (1)
Try
Driver.find_element_by_xpath ("//span[@id =\" cmitem_start\ "]"). Click ()
Except Exception as E:
Print ("Not Found")
Time.sleep (1)
Driver.close ()
Mouse hover
From selenium import Webdriver
From selenium.webdriver.common.action_chains import actionchains
Import time
Driver = Webdriver. Firefox ()
F_url = "Https://www.baidu.com"
Driver.get (F_url)
Bdmore = Driver.find_element_by_link_text ("Settings")
Actionchains (Driver). Move_to_element (Bdmore). Perform ()
Driver.find_element_by_link_text ("Search History"). Click ()
Time.sleep (2)
Driver.close ()
Mouse Double-click
Did not find the applicable scene, did not try
element = Driver.find_element_by_link_text ("xx")
Actionchains (Driver). Double_click (Element). Perform ()
Mouse Drag and drop
Did not find the applicable scene, did not try
e1 = Driver.find_element_by_xpath ("") #源位置
E2 = Driver.find_element_by_xpath ("") #目标位置
Actionchains (Driver). Drag_and_drop (E1, E2). Perform () #执行拖放
4. Keyboard events
The SendKeys can simulate keyboard input, or it can be used to simulate keys on a keyboard, even key combinations
from selenium import webdriver
from selenium.webdriver.common.by import by
from Selenium.webdriver.common.keys import keys
from selenium.webdriver.common.action_chains import Actionchains
From time import sleep,ctime
Driver = webdriver. Firefox ()
Driver.get ("https://www.baidu.com")
el = driver.find_element (by.id, "kw")
El.send_keys (" Seleniumm ")
El.send_keys (keys.back_space)
El.send_keys (keys.space)
El.send_keys (" tutorial ")
El.send_keys (Keys.control, ' a ')
El.send_keys (Keys.control, ' x ')
El.send_keys (Keys.control, ' V ')
El.send_keys (keys.enter)
Driver.close ()
Send_keys (Keys.back_space) |
Delete key backspace |
Send_keys (Keys.space) |
Space bar Space |
Send_keys (Keys.tab) |
TAB key tab |
Send_keys (Keys.espace) |
Fallback key ESC |
Send_keys (Keys.enter) |
Enter ENTER |
Send_keys (Keys.control, ' a ') |
Select All Ctrl + A |
Send_keys (Keys.control, ' C ') |
Copy Ctrl + C |
Send_keys (Keys.control, ' x ') |
Shear Ctrl+x |
Send_keys (Keys.control, ' V ') |
Paste Ctrl + V |
Send_keys (KEYS.F1) |
Keyboard F1 |
Send_keys (KEYS.F12) |
Keyboard F12 |
Problem: If you encounter the following error, it is caused by not importing keys
From Selenium.webdriver.common.keys import keys
5. Get Verification Information
Title Get page title
Current_url the current URL
Text gets the textual information between the label pairs
Driver = Webdriver. Firefox ()
Driver.get ("https://www.baidu.com")
Print (Driver.title)
Print (Driver.current_url)
Driver.close ()
6. Set the wait
6.1 Explicit wait
The display waits for the web driver to wait for a certain condition to continue executing, or to run out of the timeout exception timeoutexception. The Webdriverwait class is a wait method provided by Webdriver. During the set-up time, the default is to detect the presence of the current page element at intervals and throw an exception if it is not detected beyond the set time.
Webdriverwait (Driver, timeout, poll_frequency=0.5, Ignored_exceptions=none)
Driver: Browser driver
Timeout: Maximum time-out, default in seconds
Poll_frequency: Detection interval, default 0.5 seconds
Ignored_exceptions: Exception information after timeout, default throw nosuchelementexception exception
Webdriverwait generally used in conjunction with the until () or Until_not () method
Until (method, message= ") calls the method that provides the driver as a parameter until the return value is True
Until_not (method, message= ") calls the method supplied by the driver as a parameter until the return value is False
From selenium import Webdriver
From selenium.webdriver.common.by Import by
From time import Sleep,ctime
From Selenium.webdriver.support.ui import webdriverwait
From Selenium.webdriver.support import expected_conditions as EC #将expected_condtions重命名为EC
Driver = Webdriver. Firefox ()
Driver.get ("https://www.baidu.com")
el = webdriverwait (Driver, 5, 0.5). Until (Ec.presence_of_element_located ((by.id, "kw")) #将EC方法作为参数传入
El.send_keys (' Selenium ')
Driver.close ()
The Expected_conditions class provides the method of judging the expected condition:
Title_is |
Determines whether the title of the current page equals the expected |
Title_contains |
Determines whether the title of the current page contains the expected string |
presence_of_element_located |
Determining whether an element is added to the DOM tree does not mean that the element must be visible |
visibility_of_element_located |
The judging element is visible (the element is not hidden and the element width and height are not equal to 0) |
Visibility_of |
Same as the previous method, except that the previous method parameter is positioned, and the method receives the positioned element |
presenece_of_all_elements_located |
Determines whether at least one element exists in the DOM tree. For example, in the Baidu home page has n elements of class is Mnav, then as long as there is a existence, it returns true |
Text_to_be_present_in_element |
Determines whether the text of an element contains the expected string |
Text_to_be_present_in_element_value |
Determines whether the value property of an element contains the expected string |
Frame_to_be_available_and_switch_to_it |
Determine if the form can be toggled in, if possible, return true and switch in, otherwise return false |
invisibility_of_element_located |
Determines whether an element does not exist with the DOM tree or is not visible |
Invisibility_to_be_clickable |
Determines whether an element is visible and can be clicked |
Staleness_of |
Wait until an element is removed from the DOM tree |
element_to_be_selected |
Determines whether an element is selected and is typically used in a drop-down list |
Element_selection_state_to_be |
Determine whether an element is selected in accordance with the expected status |
Element_located_selection_state_to_be |
The same as the previous method, except that the previous method parameter is the positioned element, and the method receives the parameter as the positional |
Alert_is_present |
Determine if alert is present on the page |
6.2 Implicit wait
An implicit wait is a certain amount of time to wait for an element on the page to finish loading. Throws a Nosuchelementexception exception if the time-long element that is not set is not loaded. The Web driver provides the implictly_wait () method to implement an implicit wait, which is set to 0 by default.
Implicitly_wait (seconds)
From selenium import Webdriver
From time import CTime
Driver = Webdriver. Firefox ()
Driver.get ("https://www.baidu.com")
Driver.implicitly_wait (#设置隐式等待时间为10秒)
Try
Print (CTime ())
driver.find_element_by_id ("Kw22"). Send_keys ("Selenium")
Except Exception as E:
Print (e)
Finally
Print (CTime ())
Driver.close ()
6.3 Sleep time.sleep (seconds)
7. Positioning a group of elements
Locating a set of elements is similar to locating a single element method, except that the element is a complex number.
A scene that locates a set of elements:
1. Bulk operation elements, such as checking all the checkboxes on the page
2. First get a set of elements and then filter out the elements that need to be manipulated from this set of objects. For example, locate all the checkboxes on the page, and then select one of the actions.
DRIVER.FIND_ELEMENT_BY_ID () |
DRIVER.FIND_ELEMENTS_BY_ID () |
Driver.find_element_by_class_name () |
Driver.find_elements_by_class_name () |
Driver.find_element_by_name () |
Driver.find_elements_by_name () |
Driver.find_element_by_link_text () |
Driver.find_elements_by_link_text () |
Driver.find_element_by_partial_link_text () |
Driver.find_elements_by_partial_link_text () |
Driver.find_element_by_tag_name () |
Driver.find_elements_by_tag_name () |
Driver.find_element_by_xpath () |
Driver.find_elements_by_xpath () |
Driver.find_element_by_css_selector () |
Driver.find_elements_by_css_selector () |
ACTION check box Len () calculates the number of elements pop () is used to uncheck
Pop () Pop (-1) Gets the last one by default
Pop (index) gets the element labeled index
Example: The selection box for this page is a single selection, and clicking again cannot deselect it.
From selenium import Webdriver
From selenium.webdriver.common.by Import by
From time import Sleep,ctime
Driver = Webdriver. Firefox ()
Driver.get ("Https://www.12321.cn/web")
Stylen = Driver.find_elements_by_class_name ("Bllxcheck")
Print (len (stylen)) #打印长度4
For I in Stylen:
I.click ()
Sleep (1)
Stylen.pop (2). Click () #选择第3个选框
Driver.close ()
8. Multi-form switching
When there are multiple iframe, you can get 1 groups of elements and then do the work, you must return to the previous level.
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://sahitest.com/demo/iframesTest.htm")
IFRN = Driver.find_elements_by_css_selector ("iframe")
For I in IFRN:
Driver.switch_to.frame (i)
Driver.find_element_by_css_selector ("a[href=\" linktest.htm\ "]"). Click ()
Time.sleep (1)
Driver.switch_to.parent_frame ()
Driver.close ()
9. Multi-Window switching
During the page operation, if a new window pops up, you need to switch to the new open window. Otherwise driver still stay on the original page, the operation for the new window will be error.
Design method: Get all Handles (window_handles), current window handle (current_window_handle), switch to corresponding to window (Switch_to_handle (handle))
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://baidu.com")
Search_window = Driver.current_window_handle
Driver.find_element_by_css_selector ("div[id= ' U1 ']>a[name= ' Tj_login ']"). Click ()
Time.sleep (1)
Driver.find_element_by_link_text ("Register Now"). Click ()
Time.sleep (1)
All_handle = Driver.window_handles
For handle in All_handle:
Print (handle)
If handle! = Search_window:
Print ("Not search Window")
If handle = = Search_window:
Print ("Search window")
Driver.quit ()
10. Warning Box handling
There are 3 warning boxes, followed by alert, confirm, and prompt. Operation has accept (), dismiss (), Send_keys (value)
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://sahitest.com/demo/alertTest.htm")
Driver.find_element_by_name ("T1"). Send_keys ("Alert Test")
Alert_button = Driver.find_elements_by_css_selector ("input[type=\" button\ "]")
Print (len (Alert_button))
For AL in Alert_button:
Al.click ()
Time.sleep (1)
Driver.switch_to.alert.accept ()
Time.sleep (1)
Driver.quit ()
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://sahitest.com/demo/confirmTest.htm")
Driver.find_element_by_name ("B1"). Click ()
Time.sleep (1)
Driver.switch_to.alert.dismiss ()
Time.sleep (1)
Driver.find_element_by_name ("B1"). Click ()
Time.sleep (1)
Driver.switch_to.alert.accept ()
Time.sleep (1)
Driver.quit ()
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://sahitest.com/demo/promptTest.htm")
Driver.find_element_by_name ("B1"). Click ()
Driver.switch_to.alert.send_keys ("Hello World")
Driver.switch_to.alert.dismiss ()
Driver.find_element_by_name ("B1"). Click ()
Driver.switch_to.alert.send_keys ("Hello World")
Driver.switch_to.alert.accept ()
Driver.quit ()
10. Uploading Files
In general, Web page uploads need to open a local Windows window, and Webdriver is not able to manipulate it.
For the Web page upload functionality is generally implemented in the following 2 ways:
Normal upload: Normal attachment upload is the path of the local file as a value in the input tag, the form form to submit this value to the server
Plugin upload: Generally based on Flash, JavaScript, Ajax and other technologies implemented by the upload function
1.send_keys Implementing uploads
Did not find the right website using Send_keys upload
2. No plugin to upload files for Mac
Wait here for future additions
11. Download the file
Download file comparison Http://tool.oschina.net/commons
13. Manipulating Cookies
Sometimes it is necessary to verify that the cookie is correct, because a test based on a true cookie cannot be done through a white box or integration test.
Cookie usage Scenario: Developers develop a feature that, when the user logs in, writes the user's username to the browser cookie, the specified key is username, and we can find the corresponding value by username. If username or value is not found, the cookie is not successfully saved to the browser.
Get_cookies () Get all cookie information
Get_cookie (name) returns the cookie information for the dictionary key name
Add_cookie (cookie_dict) Here dict note the format, name, value to be specified separately
Delete_cookie (name,optionsstring)
Delete_all_cookies ()
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://www.baidu.com")
Print (Driver.get_cookies ())
Driver.add_cookie ({' name ': ' Money ', ' value ': ' Shield '})
Print (Driver.get_cookie (' money '))
#print (Driver.get_cookie (' team2 '))
Driver.delete_cookie (' money ')
Driver.delete_all_cookies ()
Driver.close ()
14. Invoking JavaScript
Although the Web driver provides a way to manipulate the browser's forward and backward methods, there is no way to manipulate the browser scroll bar. In this case, JavaScript is needed to control the browser's scrolling. Web driver provides a way for Execute_script () to execute JavaScript code.
1. Adjust the browser scroll bar
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("http://www.baidu.com")
Driver.set_window_size (600, 600)
driver.find_element_by_id ("kw"). Send_keys ("Selenium")
driver.find_element_by_id ("su"). Click ()
Time.sleep (2)
JS = "Window.scrollto (100,450)"
Driver.execute_script (JS)
Time.sleep (3)
Driver.close ()
2. Output to the Rich text box as content
Enter content into the textarea on the page. Front-end Code for text box:
<textarea id= "id" style= "width:98%" cols= "" rows= "5" class= "textarea"/>
Text = "Input text"
js = "var sum=document.getelementbyod (' id '); Sum.value= ' + text + '; '
Driver.executes_script (JS)
did not find a suitable scene, no test
15. Working with HTML video playback
https://v.autohome.com.cn/v-1930327.html #pvareaid =3311300
return arguments[0].currentsrc; Get the network storage address of the video file
return arguments[0].duration; get video length
return Arguments[0].play (); Play Video
Return Arguments[0].pause (); Pause video
From selenium import Webdriver
Import time
Driver = Webdriver. Firefox ()
Driver.get ("https://v.autohome.com.cn/v-1930327.html#pvareaid=3311300")
Print ("video title:", Driver.find_element_by_css_selector ("Div>h1"). Text)
Video = Driver.find_element_by_css_selector ("video")
Print (' pause ')
Driver.execute_script ("Return Arguments[0].pause ();", video)
Time.sleep (2)
url = Driver.execute_script ("Return arguments[0].currentsrc;", video)
Print ("Video times:", Driver.execute_script ("Return arguments[0].duration;", video))
Print ("Video url:", url)
Print (' Play ')
Driver.execute_script ("Return Arguments[0].play ()", video)
Time.sleep (2)
Driver.close ()
16. Windows
Get_screenshot_as_file ("path") will be saved as a file
Get_screenshot_as_png () This is to get the screen, save the binary data, rarely used
Get_screenshot_as_base64 ()
This method is also to get the screen, save the Base64 encoding format, in the HTML interface output, will be used.
For example, want to put in the HTML test report.
Driver.get_screenshot_as_base64 ()
river = Webdriver. Firefox ()
Driver.implicitly_wait (10)
Driver.get ("http://www.baidu.com")
driver.find_element_by_id ("kw"). Send_keys ("Selenium")
driver.find_element_by_id ("su"). Click ()
Acturetext = Driver.find_element_by_css_selector ("Span.nums_text"). Text
Expecttext = "Baidu finds relevant results for you"
Print (Acturetext)
Assert Expecttext in Acturetext, "Results not Found"
Driver.get_screenshot_as_file ("/users/chenshanju/desktop/test.png")
Driver.get_screenshot_as_png ()
Time.sleep (2)
Driver.close ()
17. Close the window
Driver.close () Close the current window
Driver.quit () Exit browser
18. Processing of verification codes
18.1 Remove the verification code
Just comment out the relevant code of the verification code. If the test environment is convenient, if the online environment, the risk is very high.
18.2 Setting the Universal Verification code
Leave a backdoor in the program and set a universal verification code. As long as the user input universal Verification code, the program is considered to pass the verification, or the user entered the verification code is correct.
From random import Randint
Verify = Randint (1000, 9999)
Number = Int (input ("Input a Number:"))
If number = = Verify:
Print ("Login Success")
elif Number = = 123456: #设置万能验证码
Print ("Login Success")
Else
Print ("Uncorrect verify")
18.3 Verification Code Identification technology
Image verification codes can be identified by Python-tesseract. However, many forms of verification code, most of the verification code recognition technology, the recognition rate is difficult to reach 100%
18.4 Recording Cookies
Driver.get ("http://www.test.com")
Driver.add_cookie ({' name ': ' Login_usernumber ', ' value ': ' Username '})
Driver.add_cookie ({' name ': ' Login_password ', ' value ': ' Password '})
Driver.get ("http://www.test.com")
Simple operation of python3+selenium3.13