F12:
Right-click to select Copy Path
In the Selenium+python Automated Test (i) – Environment setup, a test script was run with the following script:
from selenium import webdriverimport timedriver = webdriver.Chrome()driver.get("http://www.baidu.com")print(driver.title)driver.find_element_by_id("kw").send_keys("selenium")driver.find_element_by_id("su").click()time.sleep(3)driver.close()
- The first step in running the script is to open the browser and use Webdriver. Chrome () Opens Google Browser, if you want to specify a different browser, such as to use Firefox or IE browser, change the name of the browser can be
//打开Chrome浏览器driver = webdriver.Firefox() //打开Firefox浏览器driver = webdriver.Ie() //打开IE浏览器
- The second step is to open the page and use the Driver.get (URL) method to open the page links, such as the script to open Baidu home page
driver.get("http://www.baidu.com")
- Next is print (Driver.title), using Driver.title to get the current page title,title is in the browser tab display content, such as Baidu homepage title is "Baidu a bit, you know"
Browser forward Back
After opening a new link on the current page, if you want to fall back to the previous page, use the following Driver.back (), which is equivalent to clicking on the browser's Back button
And the back operation corresponds to the browser forward Operation Driver.forward (), the equivalent of clicking on the browser's forward button
//回到上一个页面driver.forward() //切换到下一个页面
After the browser runs, if the page is not maximized, you can call Driver.maximize_window () to maximize the browser, equivalent to clicking the Maximize button in the upper right corner of the page
You can also customize the size of your browser
//浏览器窗口最大化driver.set_window_size(800, 720) //设置窗口大小为800*720
After you open the page, you can take a screenshot of the page, and when you encounter an exception, you can quickly locate the problem, depending on why
Browser screenshot operation, the parameter is a screenshot of the Picture save path:
driver.get_screenshot_as_file("D:/data/test.png")
Sometimes after the page expires, the information displayed on the page may not be up to date, you need to refresh the page, refresh the page using the Refresh () method, which is equivalent to clicking the browser refresh button
driver.refresh() //重新加载页面
After the test script runs, you will typically close the browser at the end, there are two ways to close the browser, the close () method to close the current page, the Quit () method closes all browser windows related to the current test
driver.close() //关闭当前页面driver.quit() //关闭所有由当前测试脚本打开的页面
A simple test demo
About haosou.com
the test:
1 #coding =utf-8 2 from selenium import webdriver 3 import OS 4 import time
5 # Set little time stop and big time stop for viewing changes 6 Little_time_stop = 1 7 big_time_stop = 2 8 # Default banner number 9 AD S_num_require = 810 # Request Connection one by one req_url = "http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=%E9% B2%9C%E8%8A%B1 "12 # Open Browser browser = Webdriver. Chrome () 15 # Start asking for Browser.get (Req_url) 18 # get all ads All_ads_li = Browser.find_elements_by_css_selector (' #e_idea _pp Li ') 21 # Current number of banners ads_num_current = Len (all_ads_li) print "has been got%d ads"% (ads_num_current) 24 # If the number of banners does not match the default 25 If ads_num_current < ads_num_require:26 print "The number of ads is not enough (current:%d require:%d)"% (Ads_ Num_current,ads_num_require) # exit () 28 # Get top connection-i = 030 for ads_li in all_ads_li:31 time.sleep (big_time_stop) i = i+133 print "Ads%d:"%i34 try:35 main = Ads_li.find_element_by_css_selector (' h3 a ') exc ept:37 print "\terror:ads%d Cann ' t find"% (i) else:39 print "\tready:visit ads %d "% (i) Main.click () print" \tsucess:visit ads%d "% (i) time.sleep (little_time_stop) 43 try:44 Img_link = ads_li.find_element_by_class_name (' e_biyi_img ') except:46 print "\terror:no im G in ads%d "% (i) else:48 print" \tready:visit img_link%d "% (i) Img_link.click () PRI NT "\tsuccess:visit img_link%d"% (i) Wuyi time.sleep (little_time_stop) try:53 child_div = Ads_li.fin D_element_by_class_name (' E_biyi_childlink '); except:55 print "\terror:no child link in ads%d"% (i) 56 else:57 try:58 child_links = Child_div.find_elements_by_css_selector (' a ') except:60 Print "\terror:find child_links error" else:62 num_links = Len (child_links) Prin T "\tsuccess:there is%d child_links"% (num_links) j = 065 for child_a in child_links:66 j = j + 167 print "\t\tready:visit child link%d in ads%d"% (j, i) Child_a.click () 69 print "\t\tsuccess:visit child link%d in ads%d"% (j, i) Time.sleep (little_time_stop) print "En D and thanks for your using! " 72 # The following code selects Uncomment 73 # time-Lapse # Time.sleep (5) 75 # Close the current window # browser.close () 77 # Close all open Windows # Browser.quit ()
Positioning operations
The following are the APIs for all targeting operations:
Returns a matching element, which is a webelement element
FIND_ELEMENT_BY_ID ()
Find_element_by_name ()
Find_element_by_class_name ()
Find_element_by_tag_name ()
Find_element_by_link_text ()
Find_element_by_partial_link_text ()
Find_element_by_xpath ()
Find_element_by_css_selector ()
Returns a list containing all matching elements, i.e. a webelement list
FIND_ELEMENTS_BY_ID ()
Find_elements_by_name ()
Find_elements_by_class_name ()
Find_elements_by_tag_name ()
Find_elements_by_link_text ()
Find_elements_by_partial_link_text ()
Find_elements_by_xpath ()
Find_elements_by_css_selector ()
The following points should be taken into consideration when using:
- Python selenium provides two types of objects:
WebDriver
WebElement
Both of these objects can use these APIs
- Once these APIs fail to execute (that is, they are not found), an exception is thrown
The mechanism must therefore be used try: .. except: ...
to prevent the wrong behavior from affecting the program to continue
WebDriver
Call the above API for global positioning
WebElement
Calling the above API allows for hierarchical positioning, i.e.查找当前元素的子元素
Use of Webdriver
At the beginning, you have to initialize an WebDriver
instance, that is, the following to browser
control the browser and access to the page
# 请求连接
req_url = "http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=%E9%B2%9C%E8%8A%B1"
# 打开浏览器
browser = webdriver.Chrome()
# 开始请求
browser.get(req_url)
Next, you can use the exception API for global lookups of the current page, such as:
# 获取所有的广告
all_ads_li = browser.find_elements_by_css_selector(‘#e_idea_pp li‘)
Use of Webelement
Used browser.find_element_by_xx()
to get an WebElement
instance
Use the obtained instance to invoke the above API for hierarchical lookups
Used browser.find_elements_by_xx()
to get an element that is an WebElement
instance of the list
By iterating through the list, each instance can be manipulated accordingly.
Some common operations of Webdriver
browser.curren_url
: Gets the URL of the currently loaded page
browser.close()
: Closes the current window, if the current window is the last window, the browser will close
browser.quit()
: Closes all windows and stops execution of Chromedriver
browser.add_cookie(cookie_dict)
: Add a cookie for the current session
browser.get_cookie(name)
: Get Execution cookie
browser.get_cookies()
: Get all the cookies
driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’}) driver.add_cookie({‘name’ : ‘foo’, ‘value’ : ‘bar’, ‘path’ : ‘/’, ‘secure’:True})
browser.delete_all_cookies()
: Delete all cookies for the current session
browser.delete_cookie(name)
: Delete the specified cookie
browser.back()
: Equivalent to the browser's fallback history
browser.forward()
: Equivalent to the browser's forward history
browser.execute_script(script, *args)
: Synchronous execution of JS script
browser.execute_async_script(script, *args)
: Executes the JS script asynchronously
browser.get(url)
: Loads the URL in the current window
browser.refresh()
: Refreshes the current page
browser.current_window_handle
: The handle of the current window, which is the same as a pointer, to point to the current window
browser.window_handles
: All windows that are already open in the current browser are a list
browser.switch_to_window(window_handle)
: Toggles the window that window_handle points to
browser.title
: The title of the current page
browser.name
: The name of the current browser
Some common operations of webelement
webEle.clear()
: Clear the contents of the element, if this element is a text element
webEle.click()
: Click the current element
webEle,is_displayed()
: Whether the current element is visible
webEle.is_enabled()
: Whether the current element is prohibited, such as often disabling the click of some elements
webEle.is_selected()
: Whether the current element is selected, the contents of the Text input box
webEle.send_keys(*value)
: Simulates a keyboard event to the current element
webEle.submit()
: Submit Form
webEle.tag_name
: The label name of the current element
webEle.text
: The contents of the current element
webEle.get_attribute(name)
: Gets the value of the current element execution property
Selenium+python Automated Testing