This article mainly Selenium+python automatic test or crawler in the common positioning methods, mouse operation, keyboard operation introduction,Hope that the basic article is helpful to you, if there are errors or shortcomings, please Haihan ~
Previous directory:
[python crawler] install PHANTOMJS and Casperjs in Windows and introduction (top)
[Python crawler] installs pip+phantomjs+selenium under Windows
[python crawler] selenium automatically access Firefox and Chrome and implement search
[python crawler] Selenium implement automatic login 163 mailbox and locating elements Introduction
[Python crawler] SELENIUM+PHANTOMJS dynamic Get csdn Download resource information and comments
I. Positioning element Methods
Website address:http://selenium-python.readthedocs.org/locating-elements.html
here are a variety of strategies for locating elements in a Web page (locate elements), you can choose the most appropriate scenario, selenium provides a way to define the elements of a page:
- find_element_by_id
- Find_element_by_name
- Find_element_by_xpath
- Find_element_by_link_text
- Find_element_by_partial_link_text
- Find_element_by_tag_name
- Find_element_by_class_name
- Find_element_by_css_selector
here's how to find multiple elements (these methods will return a list):
- f Ind_elements_by_name
- find_elements_by_xpath
- find_elements_by_link_text
- find_elements_by _partial_link_text
- find_elements_by_tag_name
- find_elements_by_class_name
- find_elements_ By_css_selector
In addition to the public methods given above, there are two private methods that are useful in the Page object locator. These two private methods are find_element and find_elements.
The common method is to use the XPath relative path to locate, and CSS is a better method. Example:
Here's how to locate the username element:
Username = Driver.find_element_by_xpath ("//form[input/@name = ' username ']") Username = Driver.find_element_by_xpath (" form[@id = ' loginform ']/input[1] ") Username = Driver.find_element_by_xpath ("//input[@name = ' username '] ")
[1] The first FORM element is implemented by an input child element, the Name property and the value username
[2] The first input child element is found by a form element of the Id=loginform value
[3] The first INPUT element with the name of the property named name and a value of username
Two. Operation Element MethodAfter describing the anchored object (locate elements) we need to manipulate the anchored object, usually all the operations and page interaction will pass through the Webelement interface, the common operation element method is as follows:
- Clear clears the contents of an element
- Send_keys Analog Key input
- Click on the element
- Submit Form
For example, automatic access to Firefox browser automatically login 163 mailbox.
From selenium import webdriver from selenium.webdriver.common.keys import keys import time# Login 163 Emaildriver = Webdriver. Firefox () driver.get ("http://mail.163.com/") Elem_user = Driver.find_element_by_name ("username") elem_ User.clearelem_user.send_keys ("15201615157") elem_pwd = driver.find_element_by_name ("password") elem_ Pwd.clearelem_pwd.send_keys ("******") Elem_pwd.send_keys (Keys.return) #driver. find_element_by_id ("Loginbtn") ). Click () #driver. find_element_by_id ("Loginbtn"). Submit () Time.sleep (5) assert "Baidu" in Driver.title Driver.close () driver.quit ()
first locate the user name and password by name, then call the method Clear () Clear the Input box default content, such as "Please enter password" and other prompts, through Send_keys ("* *") enter the correct user name and password, and finally through click () Click the login button or Send_keys (Keys.return) is equivalent to enter login, submit () Submission form.
PS: If you need to input Chinese, prevent encoding error using Send_keys (U "Chinese user name").
three. Webelement interface Get value
Common values can be obtained through the Webelement interface, which is equally important.
- Size gets the dimensions of the element
- Text gets the literal of the element
- Get_attribute (name) Gets the property value
- Location gets the element coordinates, first finds the element to get, and then calls the method
- Page_source back to page source code
- Driver.title return page title
- Current_url gets the URL of the current page
- Is_displayed () sets whether the element is visible
- Is_enabled () Determine if the element is being used
- Is_selected () Determines whether the element is selected
- Tag_name returns the tagname of the element
The example code is as follows:
from Selenium import webdriver from Selenium.webdriver.common.keys import keys import t Imedriver = Webdriver. Phantomjs (executable_path= "G:\phantomjs-1.9.1-windows\phantomjs.exe") driver.get ("http://www.baidu.com/") size = Driver.find_element_by_name ("WD"). Sizeprint size# Size: {' width ': $, ' height ': 22}news = Driver.find_element_by_xpath ( "//div[@id = ' U1 ']/a[1]"). Textprint news# text: News href = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[2]"). get_ Attribute (' href ') name = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[2]"). Get_attribute (' name ') print Href,name #属性值: http://www.hao123.com/tj_trhao123location = Driver.find_element_by_xpath ("//div[@id = ' U1 ']/a[3]"). Locationprint location# coordinates: {' y ': +, ' x ': 498}print driver.current_url# Current Link: https://www.baidu.com/print driver.title# Title: Baidu a bit, you know result = Location = driver.find_element_by_id ("su"). is_displayed () Print result# is visible: True
where the picture is interpreted as shown.
four. Mouse Operation
In real-world automated tests, the mouse operation is more than just click (), and there are many operations included in the Actionchains class. As follows:
- Context_click (Elem) Right click on the mouse click on the element Elem, save as behavior
- Double_click (elem) Double click the mouse click on the element Elem, the map Web can achieve amplification function
- Drag_and_drop (source,target) Drag the mouse, the source element press the left key to move to the target element release
- Move_to_element (Elem) mouse moves to an element
- Click_and_hold (Elem) Press the left mouse button on an element
- Perform () performs the stored behavior in Actionchains by calling the function
For example, get the right mouse button saved as Baidu image logo. Code:
import timefrom Selenium import webdriverfrom selenium.webdriver.common.keys Import Keysfrom selenium.webdriver.common.action_chains Import actionchainsdriver = Webdriver. Firefox () driver.get ("http://www.baidu.com") #鼠标移动至图片上 right-click to save picture Elem_pic = Driver.find_element_by_xpath ("//div[@id = ') LG ']/IMG ') print elem_pic.get_attribute ("src") action = Actionchains (Driver). Move_to_element (Elem_pic) Action.context_click (elem_pic) #重点: When right mouse click keyboard cursor down then move to right menu first option Action.send_keys (Keys.arrow_down) time.sleep (3) Action.send_keys (' V ') #另存为action. Perform () #获取另存为对话框 (failed) Alert.switch_to_alert () alert.accept ()
As shown in the effect, navigate to the picture position with XPath and right-click the mouse and select "Save as Picture" in the pop-up menu. But how to click on the "Save As Dialog" button is a difficult, at present, just learning stage, the realm has not been able to solve. Reason:
Webdriver cannot directly interact with dialog Windows this was because dialog windows is the domain of the operating Syst Em and not the webpage.
This section recommends reference materials:
Selenium right-click Download image, combined with Sikuli-tobecrazy
Analysis and extension of mouse and keyboard events in Selenium Webdriver
Selenium Windows Save/open Open dialouge-stackover
Book "Selenium2 python Automation Test" bug Master
Five. Keyboard Operation
Reference: http://selenium-python.readthedocs.org/api.html
The mouse operation is described earlier and the keyboard operation is now described. All keyboard keystrokes are provided in the keys class of Webdriver, and of course include some common key combinations such as CTRL + A (select all), CTRL + C (copy), and Ctrl + V (paste). More keys refer to the encoding for the official documentation.
- Send_keys (keys.enter) Press ENTER
- Send_keys (Keys.tab) Press the Tab tab
- Send_keys (Keys.space) Press the space bar space
- Send_keys (Kyes.escape) Press the REWIND key ESC
- Send_keys (keys.back_space) Press the DELETE key backspace
- Send_keys (Keys.shift) Press the SHIFT key
- Send_keys (Keys.control) hold down the CTRL key
- Send_keys (Keys.arrow_down) Press the mouse cursor down button
- Send_keys (Keys.control, ' a ') key combination all Select Ctrl + A
- Send_keys (Keys.control, ' C ') key combination copy Ctrl + C
- Send_keys (Keys.control, ' x ') combined key shear Ctrl+x
- Send_keys (Keys.control, ' V ') bonding Ctrl + V
The examples used here refer to the insect Master's book "Selenium2 Python Automation Test", which is recommended for everyone. Code is very interesting, we have to feel the next ~
#coding =utf-8import timefrom Selenium Import Webdriverfrom Selenium.webdriver.common.keys Import keysdriver = Webdriver. Firefox () driver.get ("http://www.baidu.com") #输入框输入内容elem = driver.find_element_by_id ("kw") Elem.send_keys (" Eastmount CSDN ") time.sleep (3) #删除一个字符CSDN Rewind key Elem.send_keys (keys.back_space) Elem.send_keys (keys.back_space) Elem.send_keys (Keys.back_space) Elem.send_keys (keys.back_space) time.sleep (3) #输入空格 + "blog" Elem.send_keys (Keys.SPACE ) Elem.send_keys (U "blog") time.sleep (3) #ctrl +a Select all input box Contents Elem.send_keys (Keys.control, ' a ') Time.sleep (3) #ctrl +x Cut input Box Contents Elem.send_keys (Keys.control, ' x ') Time.sleep (3) #输入框重新输入搜索elem. Send_keys (Keys.control, ' V ') time.sleep (3) # Use the ENTER key to replace the click Operation driver.find_element_by_id ("Su"). Send_keys (Keys.enter) time.sleep (3) driver.quit ()
Finally hope that the article will help you, if there are errors or shortcomings, please Haihan ~ at the same time to learn the next Linux and the author of the article.
Http://www.dotblogs.com.tw/larrynung/archive/2012/09/26/75065.aspx
(By:eastmount 2016-7-10 1 o'clock in the afternoon http://blog.csdn.net/eastmount/)
[Python crawler] Introduction to the method and operation of common element localization in selenium