All operations in this article are performed under Windows environment

Install Python

Python is a cross-platform computer programming language that runs on Windows, Mac, and a variety of Linux/Unix systems. Is an object-oriented, dynamically typed language originally designed for writing automated scripts (shells). As versions continue to be updated and new features added to the language, To install Python, select PIP (Python package Management tool) and install PIP at the same time. After installing Python, open the command line tool CMD. Enter python -v and press Enter. If the Python version number is displayed, the installation is successful

To install selenium

Selenium is a tool for Web application testing. Selenium tests run directly in the browser, just as real users do. Supported browsers include Internet Explorer (7, 8, 9, 10, 11), Mozilla Firefox, Safari, Google Chrome, Opera, and more. Selenium is a complete set of Web application testing systems, including recording tests (Selenium IDE), writing and running tests (Selenium Remote Control), and parallel processing of tests (Selenium Grid).

Install through the Python package management tool PIP

pip install selenium

Install phantomjs

PhantomJS is a WebKit-based javaScript API. It uses QtWebKit as its core browser functionality, using WebKit to compile, interpret and execute javaScript code. Anything you can do based on the WebKit browser, it does. Not only is it an implicit browser, providing CSS selectors, support for WEN standards, DOM manipulation, JSON, HTML5, etc., but it also provides operations for handling file I/O so that you can read and write files to the operating system, etc. PhantomJS has a wide range of uses such as network monitoring, web screenshots, browser-free WEN testing, page access automation, and more

Phantomjs installation link www.phantomjs.org

Create a demo folder on your desktop, create a demo.py file, as our script file, and create an IMG folder to store the captured images

The demo. Py:
# coding=utf-8
# Import web driver software
from selenium import webdriver
# import WebDriverWait
from selenium.webdriver.support.wait import WebDriverWait
import time

Create a browser object by calling the PhantomJS browser specified by the environment variable
# Parentheses are phantomJS installation locations
driver = webdriver.PhantomJS(executable_path="D: \ \ Python27 \ \ Scripts \ \ phantomjs 2.1.1 - Windows \ \ bin \ \ phantomjs exe")
# Websites visited (take CCTV.com as an example)
driver.get("http://www.cctv.com/")
# maximize the browser
driver.maximize_window()

Click the login button to log in and the login box will pop up.
driver.find_elements_by_xpath('//span[@class="btn_icon"]') [1].click()

# wait for the login page to load, WebDriverWait
WebDriverWait(driver, 10.0.5).until(lambda diver:driver.find_element_by_xpath('//a[@class="dl"]'),message="")
time.sleep(2)
Save the page of the login box to the appropriate location
driver.save_screenshot('demo\\img\\login1.png')
Locate the login page username and password element and simulate the entry of username and password
driver.find_element_by_name("username").send_keys('xxxxxxxxxxx')
driver.find_element_by_name("passwd_view").send_keys('xxxxxxxxxxx')
Click the login button to log in
driver.find_element_by_link_text('login').click()

WebDriverWait(driver, 10.0.5).until(lambda diver:driver.find_elements_by_xpath('//span[@class="btn_icon"]'),message="")
time.sleep(2)
# Intercept the login page and save it to the corresponding location
driver.save_screenshot('demo\\img\\login2.png')

Simulate clicking the button to jump to the sports page
driver.find_element_by_link_text('sports').click()
WebDriverWait(driver, 10.0.5).until(lambda diver:driver.find_element_by_link_text('CBA'),message="")
time.sleep(2)

# Capture the sports page and save it to the appropriate location
driver.save_screenshot('demo\\img\\sport.png')

Exit driver close all Windows
driver.quit()
Copy the code
Running python scripts

Open CMD in the command line window, switch to the path of the demo.py file, and enter

python demo.py

After the script runs, it will automatically fill in the user name and password we set and log in, intercept the set page and save it to the IMG folder

Screenshot of the login page:

Screenshot of the login page:

Sports page screenshot:

Some methods:

Block location screenshot (secondary screenshot) method:

PIL(Python Image Library) is a third party Image processing Library for Python. PIL is very powerful, and its API is very simple and easy to use. PIL has become the de facto Image processing standard Library for Python platform. PIL only supports the python2.x version, python3.x version requires pillow to be installed, pillow is a PIL-friendly branch, but the python3.x version is supported

Install PIL under python2.x

pip install PIL

Install pillow under python3.x

pip install pillow

demo.py:
Import the Image class
from PIL import Image

# Locate elements that require a secondary screenshot block
img = driver.find_element_by_xpath('//*[@class="weui-img"]')
The x-coordinate of the upper left corner of the block element in the web page
left = img.location['x']
The y coordinates of the upper left corner of the block element in the web page
top = img.location['y']
The x-coordinate of the lower right corner of the block element in the web page
right = img.location['x'] + img.size['width']
The y coordinate of the lower right corner of the block element in the web page
bottom = img.location['y'] + img.size['height']
# Open a screenshot of the page
photo = Image.open('demo\\img\\img_page.png')
Implement secondary screenshots according to block element coordinates
photo = photo.crop((left, top, right, bottom))
Save the secondary screenshot
photo.save('demo\\img\\img.png')
Copy the code

WebDriver8 basic element location methods:

1. Find_element_by_id () locates based on the ID attribute

For example, find_element_by_id(“one”) locates the element with ID one

2. Find_element_by_name () locates based on the name attribute

For example, find_element_by_name(“one”) locates the element whose name attribute is one

3. Find_element_by_class_name () locates the class based on its name

For example, find_element_by_class_name(“one”) locates elements of class one

4. Find_element_by_xpath () xpath is an XML path language, which is used to locate elements in AN XML document

For example, find_element_by_xpath(“//div[@id=’one’]”) locates the div element with ID one. Find_element_by_xpath (“//*[@class=’two’]”) locates the element with class two

5. Find_element_by_css_selector () locates the CSS attributes

For example, find_element_by_css_selector(“#one”) locates the div element with ID one. Find_element_by_css_selector (“.two”) locates the element with class two

6. Find_element_by_tag_name () Locates labels based on their names

Example: find_element_by_tag_name(“input”) locates the input element

7. Find_element_by_link_text () locates according to the complete A link text
Find_element_by_partial_link_text () locates according to part A link text

For example, find_element_by_link_text(” news “) locates the a element whose text is’ news’. Find_element_by_partial_link_text (” smell “) Locates the A element whose text is’ news’

8. By positioning
(you need to import By class: the from selenium.webdriver.com mon. By the import By)

Such as: Find_element (by.id,”one”) Locates the element whose ID is one. Find_element (by.name,”one”) locates the element whose NAME is one. Locate the element find_element(by.tag_name,”div”) of class one to locate the div element

When multiple elements are located, use elements as a plural location. That is, replace element with elements, and you get a set of elements with the same attributes, return a list queue, and then locate the individual elements

For example: find_elements_by_class_name(“one”)[1] locates the second element of all elements whose class is one

There are three waiting methods for Selenium:

When doing the test automation, sometimes the next operation will depend on the results or content of the previous step, the step to the next step after successful completion of the operation, at this point, we will need to use the waiting, judge whether the step on the finish, and then perform the following operations, such as the login page to log in, need to wait for the login page loading is successful, You can locate the elements corresponding to the user name and password, and then fill in the user name and password for login.

1. Force a wait
Time.sleep (s) Forces you to wait s seconds before performing the following operations

Disadvantages: It is not easy to control the time and the waiting time is fixed. If the set time is not reached, the following operations can be carried out, then extra waiting is needed. If the set time is reached, the previous operation has not been completed, and the following operations cannot be carried out normally, an error will be reported directly

2. Implicit waiting
Implicitly_wait (s) In s seconds, the previous operation is complete and the next operation is performed. Otherwise, the implICITLY_WAIT (s) operation is performed after s

Disadvantages: If the previous step has not been completed and the following operations cannot be performed properly, an error will be reported

3. Explicit waiting (recommended)
WebDriverWait (driver, a timeout, poll_frequency = 0.5, ignored_exceptions = None)

Wait for the page to complete loading, and then continue to execute the subsequent code after a condition occurs. If it cannot be detected after the set time, an exception will be thrown

Timeout: indicates the maximum timeout period, in seconds by default. Poll_frequency: indicates the detection interval step, in seconds by default. An exception message thrown after a timeout. NoSuchElementExeception is thrown by default

Used with until() :

WebDriverWait (driver, s) until (method, message = “”)

If the method passed in returns true, proceed to the next step. If the set time is not detected, the following operations cannot run normally, and an error will be reported directly