The status quo

Haven’t updated blog for a long time, should have a month, this period of time, good busy, the company’s business in the rising period, but the following a child cut off (change group), so a lot of miscellaneous time to jb to do, basically every day alive with salty fish ~

Although it is a salted fish, but still to learn, recently in return to nature, so many years of testing dogs, or to learn some theoretical knowledge, after all, some material to blow more pleasant;

This period of time is basically learning test related books, test work, theoretical knowledge, etc., also see different test books, feel a lot of are very unsatisfactory, each book always feel lacking, if there is a chance, very want to masturbate a, ha ha ha;

Some recent projects are on the Web side. As the projects stabilize, automation will be considered later. However, selenium is basically used for PC automation

preface

I have heard about Selenium for a long time, but I still want to read it systematically. I have heard that the worm master’s book is ok, so I decided to learn about it

Although the book is called Selenium, approximately two thirds of the content is designed to test Python-related content, so we will give priority to selenium and post some information that we find useful at the end.

Note, this content is based on the original coder-pig supplement and introduction, is a collation;

Books information

Selenium 2 Automation Test Field, based on Python, published by Publishing House of Electronics Industry, January 2016

Selenium

Introduction to the

Selenium is an automated testing framework that allows you to write code that lets your browser:

  • Automatically load web pages, obtain the source code of the current page;
  • Simulate clicks and other interactions, most commonly: simulate form submission (for example, simulate login);
  • Page screenshot;
  • Determine whether certain actions occur on the page, etc.

Selenium does not support browser functionality, so it needs to be used with third-party browsers. The following browsers are supported by Selenium. You need to download the corresponding browser driver to the corresponding Python directory:

  • Chrome:sites.google.com/a/chromium….
  • FireFox:github.com/mozilla/gec…
  • PhantomJS:phantomjs.org/
  • IE:selenium-release.storage.googleapis.com/index.html
  • Edge:developer.microsoft.com/en-us/micro…
  • Opera:github.com/operasoftwa…

The installation

Install directly with the PIP command as follows:

pip install selenium
Copy the code

Then download the browser driver, most of which is Chrome. For example, other browsers can search for relevant documents by themselves. Open Chrome and type:

chrome://version
Copy the code

You can view information about the Chrome browser version, focusing on the version number:

Google Chrome 68.0.3440.106 (official version) (32-bit) (Cohort: Stable) revision 1 c32c539ce0065a41cb79da7bfcd2c71af1afe62 - refs/branch - heads / 3440 @ # {794} operating system, Windows JavaScript V8 6.8.275.26 Flash 30.0.0.154 C:\Users\ JB \AppData\Local\Google\Chrome\User Data\ PepperFlash\30.0.0.154\ PepflashPlayer.dll User agent Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit / 537.36 (KHTML, Like Gecko) Chrome/68.0.3440.106 Safari/537.36 "C: Program Files (x86)\Google\Chrome\Application\chrome.exe" --flag-switches-begin --flag-switches-end Path of the executable file C:\Program Files (x86)\Google\Chrome\Application\ Chrome C:\Users\jb\AppData\Local\Google\Chrome\User Data\DefaultCopy the code

The driver version number is 68. The driver version number is 68.

https://chromedriver.storage.googleapis.com/2.41/notes.txt
Copy the code

You can see the following version information.

----------ChromeDriver v2.41 (2018-07-27)----------
Supports Chrome v67-69
Resolved issue 2458: Chromedriver fails to start with whitelisted-ips option [[Pri-1]]
Resolved issue 2379: Returned capabilities should include remote debugging port [[Pri-2]]
Resolved issue 1005: driver.manage().window().getSize() is not implemented on Android [[Pri-2]]
Resolved issue 2474: desktop launcher error messages are not readable by users [[Pri-]]
Resolved issue 2496: Fail fast when not able to start binary [[Pri-]]
Resolved issue 1990: Close Window return value does not conform with spec [[Pri-]]
Copy the code

Ok, that is to download version 2.4.1 driver, link:

https://chromedriver.storage.googleapis.com/index.html?path=2.41/ 
Copy the code

After opening the page, you can see the page shown, select the corresponding system to download.

Download chromedriver.exe from the zip file and copy it to the Python Scripts directory. For Mac, copy the decompressed file to the usr/local/bin directory. For Ubuntu, copy the decompressed file to the usr/local/bin directory.

demo

Next, a small demo:

# coding = utf-8
In order to prevent garbled code problems, and convenient to add Chinese annotations in the program, unified coding into UTF-8.
from selenium import webdriver
Only after importing the WebDriver package can we use the WebDriver API to automate script development.
browser = webdriver.Chrome()
Assign the WebDriver Chrome object to the variable driver;
After obtaining the browser object, you can launch the browser, open the URL, and manipulate page elements. By default, the Chrome browser driver is in the Selenium WebDriver package and can be called directly.
Install the relevant browser driver first
browser.get("http://www.baidu.com")
After obtaining the browser object, use the get() method to send the url to the browser.
html_text = browser.page_source  
Get the page code
browser.quit()
Exit and close the window
Copy the code

After executing this code, Chrome automatically launches and you visit Baidu, and you can see the following prompt at the top of the browser.

And the console outputs HTML code, exactly the same structure as Chrome’s Elements page. Then you can play it this way with Selenium;

However, before getting into practice, let’s move on to some of the other selenium approaches;

API

Positioning elements

  • Find_element_by_id () : locate by ID
  • Find_element_by_name () : Locate by node name
  • Find_element_by_class_name () : locate by class
  • Find_element_by_tag_name () : Indicates the location by tag
  • Find_element_by_link_text () : Locate by the text of the link
  • Find_element_by_partial_link_text () : Locate based on partial text information between element label pairs
  • Find_element_by_xpath () : Uses Xpath to locate
  • Find_element_by_css_selector () : locate by CSS
  • Find_element (BY.xx,value) : Declares the location method based on By and passes in the location parameters of the corresponding location method, such as BY. ID and by.class_name

Alternatively, changing element to elements will locate all eligible elements and return a List, such as:

find_elements_by_class_name
Copy the code

Selenium locating the node returns an object of type WebElement, and you can call the following methods to extract the required information.

  • Get attributes:element.get_attribute()
  • Get text:element.text
  • Get the tag name:element.tag_name
  • Get node ID:element.id

Control window size

Driver.set_window_size (480,800) : # Display driver.maximize_window()Copy the code

Page forward, back, switch

In the page operation process sometimes click a link will pop up a new window, at this time need to switch to the newly opened window for operation;

For handle in driver. Window_handles: Driver.switch_to_window (handle) # Switch window driver.switch_to.window(" window name ") # or through window_handles for handle in Driver.window_handles: driver.switch_to_window(handle) # forward driver.forward() # backward driver.back()Copy the code

The refresh action

driver.refresh()
Copy the code

Clear text, simulate key input, click action

Driver.find_element_by_id (" IDINPUT "). Clear () # send_keys() is used to simulate keyboard input into the input field Driver.find_element_by_id (" idINPUT ").send_keys("username") # click( driver.find_element_by_id("loginbtn").click()Copy the code

Submit the form

Driver.find_element_by_id ("query").submit()Copy the code

Mouse action

Sometimes you need to simulate mouse action on a page, for example: Click, double-click, right-click, hold and drag and drop, etc., can be imported ActionChains classes: selenium.webdriver.com mon. Action_chains. ActionChains, Use ActionChains(driver).xxx to invoke the behavior of the corresponding node.

  • Click (Element) : Click on a node;
  • Click_and_hold (element) : Click on a node and hold;
  • Context_click (Element) : right click on a node;
  • Double_click (element) : Double-click a node;
  • Drag_and_drop (source,target) : Hold down a node and drag it to another node;
  • Drag_and_drop_by_offset (source, xoffset, yoffset) : Hold and drag the node as offset
  • Key_down: Press a special key (Control, Alt and Shift only), such as Ctrl+C
  • ActionChains (driver). Key_down (Keys. The CONTROL). Send_keys (‘ c ‘). Key_up (Keys. The CONTROL). The perform ();
  • Key_up: releases special keys.
  • Move_by_offset (xoffset, yoffset) : Press the offset to move the mouse.
  • Move_to_element (element) : Moves the mouse to a node;
  • Move_to_element_with_offset (element, xoffset, yoffset) : Move the cursor to a node and offset;
  • Pause (second) : The number of seconds for which all input is paused;
  • Perform () : Perform operations. Multiple operations can be set before a call to perform() is performed.
  • Release () : Release the mouse button
  • Reset_actions: Resets operations
  • Send_keys (keys_to_send) : simulate Keys, such as input box node send_keys(keys.control,’a’) Select all input box contents, input box node Send_keys (keys.control,’x’) cut, simulate back: Node. Send_keys (keys. RETURN); Or set the contents of the input box directly: input box node.
  • Send_keys_to_element (element, *keys_to_send) : Similar to send_keys;

Keyboard events

Send_key () simulates keyboard typing, but other Keys, such as space, are needed. Corresponding class: selenium.webdriver.com mon. Keys. Keys, use send_keys (keys. XX) input the content of the corresponding;

  • BACK_SPACE: delete key(BackSpace) (send_key(keys.back_space))
  • SPACE: SPACE
  • TAB: TAB key
  • ESCAPE: The back key (Esc)
  • ENTER: Press ENTER.
  • CONTROL,’a’ : Select all (Ctrl+A) (send_key(keys. CONTROL,’a’))
  • CONTROL,’c’ : Copy (Ctrl+C)
  • CONTROL,’x’ : Cut (Ctrl+X)
  • CONTROL,’v’ : Paste (Ctrl+V)
  • F1: keyboard F1
  • .
  • F12: Keyboard F12

Page title and link

Driver.title # Obtain the url of the current page driver.current_urlCopy the code

Page waiting

As Web pages increasingly use Ajax technology, applications can’t be sure when an element is fully loaded. If the actual page waits too long for a DOM element to appear, but your code uses the WebElement directly, NullPointer will be raised. In order to avoid the difficulties and will improve the element orientation ElementNotVisibleException probability. So Selenium provides two waiting modes, one is implicit and the other is explicit.

  • Explicit wait: Specify a condition and then set the maximum wait time. If the element is not found at this time, an exception is thrown as shown in the following code:
The from the selenium import webdriver from selenium.webdriver.com mon. By the import by # WebDriverWait library, . Responsible for circular wait from the selenium webdriver. Support. The UI import WebDriverWait # expected_conditions class, Responsible for conditions from the selenium. Webdriver. Support the import expected_conditions as EC driver = webdriver. PhantomJS () driver.get("http://www.xxxxx.com/loading") try: Id ="myDynamicElement", Element = WebDriverWait(driver, 10). Until (ec.presence_of_element_located ((by.id, "myDynamicElement")) ) finally: driver.quit()Copy the code

If no arguments are written, the program defaults to a 0.5 second call to see if the element has been generated, and returns immediately if the element already exists. Here are some of the built-in wait conditions that you can invoke directly instead of writing your own wait conditions.

Waiting on the condition describe
title_is The title is the content
title_contains The title contains something
presence_of_element_located The node is loaded and passed the location tuple
visibility_of_element_located Node courseware, passed location tuple
visibility_of See, pass in the node object
presence_of_all_elements_located All the nodes are loaded
text_to_be_present_in_element A node text contains a text
text_to_be_present_in_element_value A node value contains a literal
frame_to_be_available_and_switch_to_it Load and switch
invisibility_of_element_located The node is not visible
element_to_be_clickable Nodes are clickable
staleness_of Determining whether the node is still in the DOM is often used to determine whether the page has been refreshed
element_to_be_selected Node optional, pass in node object
element_located_to_be_selected The node is optional, passing in the positioning tuple
element_selection_state_to_be Pass in node object and state, return True if equal, False otherwise
element_located_selection_state_to_be Pass in location tuples and state, return True if they are equal, False otherwise
alert_is_present Is there a warning?
  • Implicit wait: Implicit wait is relatively simple. It is simple to set a wait time in seconds. The code example is as follows:
from selenium import webdriver driver = webdriver.PhantomJS() driver.implicitly_wait(10) # seconds Driver. The get (" http://www.xxxxx.com/loading ") myDynamicElement = driver. Find_element_by_id (" myDynamicElement ") if not set, The default wait time is 0Copy the code

Sleep sleep

Sleep () is used when you want a script to sleep for a fixed period of time. The sleep method is provided by Python’s time module, so from time import sleep is required before using it.

Sleep (X)Copy the code

Multi-form switching

In Web applications, frame/ IFrame forms are often used to nest pages. Webdriver can only identify and locate elements on a page, but cannot locate frame/ IFrame directly.

In this case, you need to use the switch_to.frame() method to switch the currently located body to the frame/iframe embedded page.

# Switch to iframe(id = "XX") driver.switch_to.frame("XX")Copy the code

After the switch, elements can be manipulated normally.

Switch_to.frame () can get the id or name attributes of the form directly by default, but what if iframe does not have id and name attributes available?

Find_element_by_xpath ("//*[@class="XX"]") # Switch_to.frame ( driver.switch_to.frame(xf)Copy the code

Popup window

Corresponding class: selenium.webdriver.com mon. Alert. Alerts and use very much, if you trigger an event, the pop-up dialog box, you can call this method to get the dialog: Alert = driver.switch_to_alert(), then the alert object can call the following methods:

  • Accept () : sure
  • Dismiss () : Close the dialog box
  • Send_keys () : Incoming value
  • Text () : Gets the dialog box text

Upload a file

General web upload files, there is a browse button, select the file click upload, but corresponding to the automatic test, in the selection of file that process is very troublesome;

If you’ve done this before, you’ll notice that the browse button is actually an input box. Send_keys () can be used to simulate this.

driver.find_element_by_name("file").send_keys("C:\\jb.txt")
Copy the code

The download file

Run setup file download path;

options = webdriver.ChromeOptions() prefs = {'profile.default_content_settings.popups': 0, 'download.default_directory': os.getcwd()} options.add_experimental_option('prefs', prefs) driver = webdriver.Chrome(chrome_options=options) Driver. The get (" http://pypi.Python.org/pypi/selenium ") driver. Find_element_by_partial_link_text (" selenium - 3.11.0 - py2. Py3 - none -any").click()Copy the code

Page screenshots

Dirver.get_screenshot_as_file ("C:\\jb\ jb.jpg") # screenshot_as_file("C:\\jb\ jb ")Copy the code

Cookies

Some sites need to be logged in to access them. It is very common to use Selenium to simulate logging in to get Cookies and use them for crawlers. Selenium provides functions to get, add, and delete Cookies, as shown in the following code:

Browser. Get_cookie (name) # add Cookies, is a dictionary object, Add_cookie ({"name":"jb","value":"jbtest"}) driver. Add_cookie ({"name":"jb","value":"jbtest"})  for cookie in driver.get_cookies(): Print ("%s -> %s "% (cookie["name"],cookie["value"])) Name is the name of the cookie to delete, and optionsString is the option for the cookie. Currently supported options include "path" and "domain" browser.delete_cookie(name,optionsString)Copy the code

Practice:

from selenium import webdriver browser = webdriver.Chrome() url = "https://www.baidu.com/" browser.get(url) # Newwindow ='window.open("https://www.baidu.com"); Add_cookie ({'name':'ABC','value':'DEF'}) # Open a new window through JS Browser.execute_script (newwindow) input(" View the effect ") browser.quit()Copy the code

Here still need to say, the add_cookie method accepts a dictionary, the dictionary contains the name, value, path, domain, secure, expiry,

Correct format for writing cookies:

Cookie = {# "domain": ".58.com", #Firefox browser can not write domain, if it is written, it will return an error, Google need to write otherwise, it will return an error, this is a trap. Other browsers don't know without testing. 'name': name, 'value': value, "expires": "", 'path': '/', 'httpOnly': False, 'HostOnly': False, 'Secure': False,} name: name of the cookie value: dynamically generated value of the cookie Domain: server domain name expiry: Cookie valid expiration date Path: The Path attribute defines which pages on the Web Server can obtain the Cookie set by the Server. HttpOnly: Prevents scripting attacks. Secure: Marks this variable in the Cookie, indicating that the communication protocol between the browser and the Web Server is encrypted authenticationCopy the code

The reason for this is to look at the format of the cookie saved by the browser. Here is a screenshot of Google’s Browser cookie.

The code should look like this:

There is a problem here. It is very troublesome to use the key:value format of cookies, especially very long cookies like Douban, and then manually change the format one by one. It is less workload than re-writing a login operation using Selenium.

The cookie format for the fiddler subpackage looks like this:

One change at a time will collapse; So encounter a long cookie, it is better to write a login script save ~

Execute JS statements

Although WebDriver provides the browser forward and backward, but does not provide the operation of scrolling browser, so to use JS to control the browser scroll bar;

Driver. Execute_script (js)Copy the code

An example of code for scrolling to the bottom is as follows:

js = document.body.scrollTop=10000
driver.execute_script(js)
Copy the code

Or setting the browser window scroll bar position:

Js = "window. ScrollTo (100450)" driver. Excute_script (js)Copy the code

Enter text information into a text box:

text = "jbtest"
js = "var sum=document.getElementById("id"); sum.value='"+text+ " ';"
driver.excute_script(js)
Copy the code

Handling HTML5 video playback

HTML5 defines a new element, video, that specifies a standard way to embed movie clips;

from selenium import webdriver from time import sleep driver = webdriver.Firefox() driver.get("http://videojs.com/") Video = driver.find_element_by_xpath("body/Setion[1]/div/video") # arguments[0].currentSrc;" Execute_script ("return arguments[0].play()",video) # Pause video driver.execute_script("arguments[0].pause()",video)Copy the code

JS functions have a built-in object called Arguments; The arguments object contains an array of function call arguments. [0] takes the first value of the object.

  • CurrentSrc: Returns the URL of the current audio/video, or an empty string if no audio/video is set;
  • Load () : Controls the loading of the video
  • Play () : Controls the playback of the video
  • Pause () : Controls the pause of a video

Headless

Before introducing Headless, PhantomJS is a browser with no interface. PhantomJS features a web site that loads into memory and executes JavaScript on the page, and runs more efficiently than a full browser because it doesn’t display a graphical interface

In the example above, after each execution, the browser is opened, which is very troublesome, so PhantomJs is just needed;

But PhantomJs is not going to be covered here, because in April of ’18, the maintainer announced that PhantomJs was no longer maintained; At the same time, Chrome and FireFox also started offering Headless mode (no need to tune up the browser), so the phantomJS companion will migrate to those two browsers;

Note: Windows Chrome needs to be at least 60 to support Headless mode. Linux and Unix require Chrome >= 59

Enabling Headless mode is also very simple, using the above code to open Baidu for example, the code is as follows:

from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_option = Options() chrome_option.add_argument("--headless") chrome_option.add_argument("--disable-gpu") browser = Webdriver.Chrome(chrome_options=chrome_option) # Call local Chrome browser browser.get('http://www.baidu.com') # request page, Browser.quit () # Close the browser print(html_text)Copy the code

Chrome_option = chrome_option = chrome_option = chrome_option

Sets the custom request header

From Selenium import webdriver # Enter the browser and set options = webdriver.chromeOptions () # set Chinese Add_argument ('user-agent="Mozilla/5.0 (iPod; U; CPU iPhone OS 2_1 like Mac OS X; Ja - jp) AppleWebKit / 525.18.1 (KHTML, Like Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20"') browser = webDriver.Chrome(chrome_options=options) URL = "https://httpbin.org/get?show_env=1" browser.get(url) browser.quit()Copy the code

Selenium is a brainless type, and its efficiency is relatively poor. If you have 1W websites, it will take a day to run them all.

With most selenium related operations covered, let’s take a look at how selenium can be used to obtain the property of the Bean verification code captCHA.

"Cookie":"your Cookie" # enter your own Cookie information. If you encounter an escape character, add \ before the escape characterCopy the code

Selenium

What is the Selenium

Selenium is primarily used for automated testing of Web applications;

Features:

  • Open source, free;
  • Multi-browser support: Firefox, Chrome, IE, Opera, Edge;
  • Multi-platform support: Linux, Windows, MAC;
  • Multi-language support: Java, Python, Ruby, C#, JavaScript, C++;
  • Good support for Web pages;
  • Simple and flexible API (driven by development language)
  • Support distributed test case execution

Selenium comes in two versions: Selenium 1.0 and Selenium 2.0. Selenium is not made up of a single tool, but a number of plug-ins and class libraries, each with its own features and application scenarios.

Selenium 1.0 Family Tree:

Selenium IDE

Selenium IDE is a plug-in embedded in the Firefox browser that enables the recording and playback of simple browser operations.

The official definition of its role:

Quickly create bug replay scripts. During the testing process, testers can record the replay steps after finding bugs, so as to help developers more easily replay bugs.Copy the code

It makes sense, then, that the IDE is focused on recording to avoid students who can’t write code, and that writing aN xpath every time is annoying;

The installation

Online installation access Selenium through the Firefox browser;

Download page: docs.seleniumhq.org/download/

In the Selenium IED download introduction section, click the version number link;

The Firefox browser will automatically recognize the Selenium IED plug-in that needs to be downloaded. Click the Install Now button to Install the Selenium IED plug-in.

After the installation is complete, restart Firefox. To open it, choose Tools > Selneium IDE on the menu bar, or press Ctrl+Alt+S to open it.

But in fact, the above URL, tried for a long time, can not access, also, if not Firefox browser is not IDE?

Plug-in installation is not also, there is a plug-in installation method, this method from xiaomin students pro test feasible, Python2.7 version, Firefox40.0 version;

Python2.7 for MAC /Linux Windows need manual installation, to install small partners to their own degrees, so easy ~

Since Selenium IDE is not supported in the new version of Firefox, it is quite difficult to write without the recording function. It is recommended to be conservative and choose the old version.

If you have selenium3 installed, you need to uninstall it;

PIP show selenium Uninstall Selenium command PIP uninstall SeleniumCopy the code

Selenium: PIP install Selenium ==2.53.6 Selenium ==2.53.6

  • Download the installation package selenium-2.53.6.tar.gz
  • Place the installation package in python2.7’s site-packages directory and unzip it, such as /Library/Python/2.7/site-packages/
  • CD Go to the selenium directory decompressed in the previous step and run Python setup.py install. The installation is complete. Check the version number to confirm the installation

3) Download and install Firefox 40.0

4) Download selenium_IDE-2.1.1-Fx. xpi and drag it to Firefox. After installing it, the Selenium IDE plug-in entry will be displayed in the upper right corner of Firefox

5) Download Firebug-2.0.16-Fx. xpi and drag it to Firefox. After installing it, the firebug plugin entry will appear in the upper right corner of Firefox

At this point, the environment is installed.

Click the Selenium IDE plug-in icon in the upper right corner of Firefox to enter the Selenium IDE main interface.

  • Enter the WEB URL you want to test in the red box of number 1 below.
  • In the red box of number 2 below, adjust the speed at which you want to execute the use case.
  • Click the record button in the red box no. 3 below to start recording;
  • In the red box no. 4 in the figure below, adjust the recording result by adding, deleting and modifying events and parameters.
  • Click the stop recording button in the red box no. 3 below to stop recording;
  • Click the button in the red box of number 5 below to start executing the use case.
  • You can select the file — export test case as — python 2/unittest/ Web Driver from the menu to export the script as Python. The script is directly invoked by local editing.

7) Optimization script The last exported script in the previous step only contains operations, does not contain assertion result judgment, and lacks fault tolerance. If you want continuous integration to automatically generate results, you need to supplement them as needed.

Selenium Grid

Grid is an automatic test aid. Grid can speed up the functional testing of Web-apps by leveraging existing computer infrastructure.

Using Grid, test cases can be easily run on multiple machines and in heterogeneous environments.

As confusing as it may sound, Selenium Grid addresses the highlights of repeated execution testing and multi-browser compatibility testing using distributed execution testing.

What is distributed? Simply said that the boss received the task, distributed to the hand to dry;

Selenium Grid allows you to control the execution of test cases on multiple machines and browsers. The distributed execution environment is called node node in Selenium Grid.

For example, with tens of thousands of use cases, it takes 5 hours for one machine to execute all the test cases, while it takes 10 hours to cover mainstream browsers like Chrome and Firefox.

The dumbest way to do this is to take another machine, deploy the environment, execute the test cases separately and merge the results.

Selenium has figured this out, so Selenium Grid has emerged to solve the pain point of distributed test execution.

The working principle of

Selenium Grid is actually based on Selenium RC, and the so-called distributed structure consists of a hub node and several Node agent nodes.

The Hub manages the registration and status information of each proxy node, accepts requests from the remote client code, and forwards the requested commands to the proxy node for execution.

The following describes the relationship between Hub and Node nodes based on the environment deployment.

The deployment environment

1) download the selenium server – standalone – 2.53.1. Jar

Download address: selenium-release.storage.googleapis.com/index.html

2) start the hub

Use the shortcut key WIN+R to open the run dialog box and enter CMD to enter the command window

Enter the location of the selenium-server-standalone 2.53.1.jar package, such as E:\selenium;

Start the hub with the following command:

Java-jar selenium-server-standalone-2.53.1.jar -role hub -maxSession 10-port 4444Copy the code

parameter explain
role hub Start running the hub
port Set the port number. The default port for the hub is 4444. The default port is used here
maxSession Maximum session request. This parameter is used for concurrent execution test cases. The default value is 1

Browser address: http://localhost:4444/grid/console, said in the diagram below hub started successfully.

After starting the hub, you need to run the node, at least there should be a node, otherwise the hub will become a commander; The node node can run on the same machine as the hub, demonstrating that one node is on the same machine as the hub and the other node starts a virtual machine.

The name of the IP
The hub machine 192.168.0.245
Node1 machine 192.168.0.245
2 machine 192.168.0.183

3) Start node 1

On the node1 node, configure The Firefox browser and run the following command:

Java jar selenium - server - standalone - 2.53.1. Jar - role node - port 5555 - hub at http://192.168.0.245:4444/grid/register -maxSession 5 -browser browserName= Firefox,seleniumProtocol=WebDriver,maxInstances=5, Platform =WINDOWS,version=45.0.2Copy the code

No error is refresh again visit http://localhost:4444/grid/console will find node node have shown that says start success;

parameter explain
role node Start the running node
port 555 Specify node Node port
hub http://192.168.0.245:4444/grid/register The hub machine address
maxSession 5 Node Maximum session request of a node
Browser browserName = firefox, seleniumProtocol = WebDriver, maxInstances = 5, platform = WINDOWS, version = 45.0.2 This is setting the browser parameters
MaxInstances indicates the maximum number of browsers that can run. The value cannot be greater than the previous value of maxSession; otherwise, errors may occur. Platform stands for operating system. Version Indicates the browser version.Copy the code

4) Start node 2

Chromedriver. exe is a chromedriver that can be installed in the chrome browser on the node2 node.

Java jar selenium - server - standalone - 2.53.1. Jar - role node - port 6666 - hub at http://192.168.0.245:4444/grid/register -Dwebdriver.chrome.driver=chromedriver.exe -maxSession 5 -browser browserName=chrome,seleniumProtocol=WebDriver,maxInstances=5,platform=WINDOWSCopy the code

No error is refresh again visit http://localhost:4444/grid/console will find node node have shown that says start success;

If the Chromedriver. exe file does not match selenium-server-standalone-2.53.1 or chrome, an error message is displayed.

parameter explain
Dwebdriver.chrome.driver=chromedriver.exe Browser plugin, if it is another browser to write the corresponding name
Such as firefox: - Dwebdriver. Firefox. Driver = geckodriver. Exe much more attention to note that this parameter is to chromedriver. Exe need to specify, Webdriver2 supports GeckoDriver, so you do not need to specify geckodriver. However, the firefox version cannot be later than 46. Therefore, Node 1 uses browser version 45.Copy the code

use

When the Hub remote is instantiated, it will match the node proxy node registered on the Hub according to the configuration, and forward the match to the proxy node. At this time, the proxy node will generate the sessionID to start the browser, and then respond to the Hub that everything is ready, and the Hub will also respond to the sessionID to the client. Subsequent requests from client code are forwarded by the Hub to the proxy node for execution. In this case, the entire process is essentially the same as Selenium1.0, but with the additional Hub layer.

DesiredCapabilities capability = new DesiredCapabilities();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
try {
WebDriver driver = new RemoteWebDriver(new URL("http://192.168.0.245:4444/wd/hub"), capability);
driver.get("http://www.baidu.com");
driver.quit();
} catch (MalformedURLException e) {
  e.printStackTrace();
}
Copy the code

If you change setBrowserName(), Firefox will execute it on Node 1. It indicates that the Selenium Grid environment is set up.

In addition, the client can run the code directly using the Node node, which is exactly the same as selenium1.0.

DesiredCapabilities capability = new DesiredCapabilities();
capability.setBrowserName("chrome");
capability.setPlatform(Platform.WINDOWS);
try {
WebDriver  driver = new RemoteWebDriver(new URL("http://192.168.0.183:6666/wd/hub"), capability);
driver.get("http://www.baidu.com");
driver.quit();
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Copy the code

Note that when instantiating the driver object, the service address is the address of the Node node, which will run directly on the node. DesiredCapabilities configuration, be sure to set the node to run the correct parameters of the browser, browser version, and system, if the parameters are not correct will display an error.

Selenium RC

Selenium RC(Remote Control) is the core part of Selenium family. Automated test scripts written in many different languages are supported. Selenium RC servers serve as proxy servers to access applications for testing purposes.

Selenium RC is divided into Client Libraries and Selenium Server. The Client Libraries library is mainly used to write test scripts that control selenium Server Libraries. Selenium Server is responsible for controlling browser behavior;

In general, Selenium Server consists of three main parts: Launcher, Http Proxy, and Core.

Selenium Core is embedded in the browser page by Selenium Server. Selenium Core is a collection of JS functions that allow you to programmatically manipulate the browser.

The Launcher is used to launch the browser, load Selnium Core into the browser page, and set the browser Proxy as Selenium Server’s Http Proxy.

The Selenium 2.0

Selenium 2.0 adds WebDriver to the family; It can be simply expressed as:

Selenium 2.0 = Selenium 1.0 + WebDriver

In Selenium 2.0, WebDriver is the main push. WebDriver is an alternative to Selenium RC. So what are the main differences between Selenium RC and WebDriver?

Selenium RC runs JavaScript applications in the browser, using the browser’s built-in JavaScript translator to translate and execute Selenium commands.

WebDriver directly controls the browser through native browser support or browser extensions.

WebDriver is developed for each browser and replaces JavaScript embedded in the Web application under test. Tight integration with the browser enables the creation of more advanced tests, avoiding the limitations imposed by the JavaScript security model. In addition to support from browser vendors, WebDriver also simulates user input using operating system-level calls.Copy the code

WebDriver principle

WebDriver is designed according to the server-client design pattern.

The Server side is Remote Server, which can be any browser. When our script launches the browser, it becomes the Remote Server and waits for the Client to send a request and respond.

The Client side is simply the test code; The behavior of the script is sent to the tested browser in the form of HTTP request. The browser accepts the request, performs the corresponding operation, and returns the execution status and other information in response.

WebDriver workflow:

  • WebDriver starts the target browser and binds it to the specified port. The browser instance launched will act as the Remote Server for WebDriver;
  • CommandExcuter sends HTTPRequest to Remote Server’s listening port;
  • Remote Server relies on native browser components to translate native browser calls;

summary

Intermittently read this book for a long time, or because of their lazy;

After reading this book, you should have at least an impression of the Selenium API. The most important thing is that there are eight ways to find controls. If Jb is going for an interview, he will also ask this question.

Remember that Selenium is a good way to get javascript loaded page content. If you want to crawl a web page that has JS loaded content, use Selenium if you don’t want to study JS.

Set up a flag. I was so busy that I didn’t update my blog for a month, and I felt like a loser. So set up a flag and update it once a week to see how long it lasts

Finally, post this link to the electronic version of the book:

https://pan.baidu.com/s/1b8T6Iq?errno=0&errmsg=Auth%20Login%20Sucess&&bduss=&ssnerror=0&traceid=
Copy the code

Just to clarify, the digital version is still a little different from the physical book. If you just use it to check the API, read this article or read the ebook, the main content is the same;

Thank you.