Scene
The positioning and operation of the test object is the core content of Webdriver, and the operation is based on the positioning, so the object positioning becomes more and more important.
The purpose of locating objects generally has the following types of
- Manipulating objects
- Gets the properties of the object, such as the class property of the test object, the Name property, and so on
- Gets the text of the object
- Get the number of objects
Webdriver provides a series of object positioning methods, commonly used in the following several
- Id
- Name
- Class name
- Link text
- Partial link text
- Tag name
- Xpath
- CSS Selector
Code login.html
<! DOCTYPE html> Python code #!/usr/bin/env python#-*-coding:utf-8-*-"' Created on 2018/5/9 11:35@author:jeff lee@file: Simple object positioning. py ' from selenium Import webdriverfrom Time import sleepimport osif ' Http_proxy ' in Os.environ:del os.environ[' http_proxy ']dr = Webdriver . Firefox () File_path = ' file://' + os.path.abspath (' login.html ') print (File_path) dr.get (File_path) # by Idprint (' Locate by id ') dr.find_element_by_id (' username '). Click () sleep (1) # by Nameprint (' Locate by name ') Dr.find_element_by_name (' Password '). Click () sleep (1) # by Tagnameprint (' position by tag ') print (Dr.find_element_by_tag_name (' form '). Get_attribute ( ' ID ')) sleep (1) # by Class_nameprint (' Position by class ') E = dr.find_element_by_class_name (' Form-control ') try:dr.execute_ Script (' $ (arguments[0]). FadeOut (). FadeIn () ', E) except Exception as E:print (' No JS ') sleep (1) # By Link textprint (' via link Text to position ') Link = dr.find_element_by_link_text (' Forgot password? ') Try:dr.execute_script (' $ (arguments[0]). FadeOut (). FadeIn () ', link) except Exception as E:print (' No JS ') sleep (1) # by Partial link Textprint (' Navigate through some link text ') Link = dr.find_element_by_partial_link_text (' Forget ') Try:dr.execute_script (' $ (arguments[0 ]). FadeOut (). FadeIn () ', link ' except Exception as E:print (' No JS ') sleep (1) # by CSS Selector#print (' positioning via CSS selector ') ) #div = Dr.find_element_by_css_selector ('. Controls ') #dr. Execute_script (' $ (arguments[0]). FadeOut (). FadeIn () ', div) #sleep (1) # by Xpathprint (' position by XPath ') Dr.find_element_by_xpath ('/html/body/div/form/div[3]/div/div/input '). Click () Sleep (2) dr.quit ()
Discussin the above example becauseHTMLfile that references thejquery, so in the executionJSwhen you can usejqueryof the$()andfadeIn ()and other methods. If the page you're testing doesn't containjquery, these methods are invalid.
Python+selenium Learning--Simple object positioning