Selenium+python Automated Testing

Source: Internet
Author: User

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() //切换到下一个页面
    • Maximize browser window

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
    • Screen

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")
    • Page Refresh

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() //重新加载页面
    • Exit browser

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:

    1. Python selenium provides two types of objects: WebDriver WebElement
      Both of these objects can use these APIs
    2. 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
    3. WebDriverCall the above API for global positioning
      WebElementCalling 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

    1. # 请求连接
    2. req_url = "http://www.haosou.com/s?ie=utf-8&shb=1&src=360sou_newhome&q=%E9%B2%9C%E8%8A%B1"
    3. # 打开浏览器
    4. browser = webdriver.Chrome()
    5. # 开始请求
    6. browser.get(req_url)

Next, you can use the exception API for global lookups of the current page, such as:

    1. # 获取所有的广告
    2. all_ads_li = browser.find_elements_by_css_selector(‘#e_idea_pp li‘)
Use of Webelement
    1. Used browser.find_element_by_xx() to get an WebElement instance
      Use the obtained instance to invoke the above API for hierarchical lookups

    2. 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
  1. browser.curren_url: Gets the URL of the currently loaded page
  2. browser.close(): Closes the current window, if the current window is the last window, the browser will close
  3. browser.quit(): Closes all windows and stops execution of Chromedriver
  4. 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})
  5. browser.delete_all_cookies(): Delete all cookies for the current session
    browser.delete_cookie(name): Delete the specified cookie

  6. browser.back(): Equivalent to the browser's fallback history
  7. browser.forward(): Equivalent to the browser's forward history
  8. browser.execute_script(script, *args): Synchronous execution of JS script
    browser.execute_async_script(script, *args): Executes the JS script asynchronously
  9. browser.get(url): Loads the URL in the current window
  10. browser.refresh(): Refreshes the current page
  11. browser.current_window_handle: The handle of the current window, which is the same as a pointer, to point to the current window
  12. browser.window_handles: All windows that are already open in the current browser are a list
  13. browser.switch_to_window(window_handle): Toggles the window that window_handle points to
  14. browser.title: The title of the current page
  15. browser.name: The name of the current browser
Some common operations of webelement
      1. webEle.clear(): Clear the contents of the element, if this element is a text element
      2. webEle.click(): Click the current element
      3. webEle,is_displayed(): Whether the current element is visible
      4. webEle.is_enabled(): Whether the current element is prohibited, such as often disabling the click of some elements
      5. webEle.is_selected(): Whether the current element is selected, the contents of the Text input box
      6. webEle.send_keys(*value): Simulates a keyboard event to the current element
      7. webEle.submit(): Submit Form
      8. webEle.tag_name: The label name of the current element
      9. webEle.text: The contents of the current element
      10. webEle.get_attribute(name): Gets the value of the current element execution property
 

Selenium+python Automated Testing

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.