Introduction and practice of Python+Selenium Foundation

Posted by rakennedy75 on Mon, 24 Jan 2022 06:31:16 +0100

1, Selenium+Python environment construction and configuration

1.1 introduction to selenium

Selenium is a web automated testing tool. Many students who study functional automation begin to prefer selenium because it has many advantages over QTP:

  • Free, and you don't have to worry about cracking QTP
  • Compact, it is just a package for different languages, and QTP needs to download and install more than 1 G program.
  • This is also the most important point. No matter you are more familiar with C, java, ruby, python, or C #, you can use selenium
    Complete automated testing, while QTP only supports VBS
  • Support multiple platforms: windows, linux, MAC, and support multiple browsers: ie, ff, safari, opera, and chrome
  • Support the execution of distributed test cases. Test cases can be distributed to different test machines for execution, which is equivalent to the function of distributor.

1.2 selenium+Python environment configuration

Prerequisite: Python development environment has been installed (Python 3.5 and above are recommended)
Installation steps:

1. Install selenium

Win: pip install selenium

Mac: pip3 install selenium

2. Install webdriver

  1. Firefox: https://github.com/mozilla/geckodriver/releases/
  2. Chrome: https://sites.google.com/a/chromium.org/chromedriver/ Or http://chromedriver.storage.googleapis.com/index.html
  3. IE: http://selenium-release.storage.googleapis.com/index.html

Note: webdriver should correspond to the corresponding browser version and selenium version

3.webdriver installation path

Win: copy webdriver to Python installation directory

Mac: copy webdriver to / usr/local/bin directory

2, Element positioning and basic operation of browser

2.1 launch browser

2.1.1 normal mode startup

  1. Launch Chrome browser:
from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://www.baidu.com/')
  1. Launch Firefox browser:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.baidu.com/')
  1. Start IE browser:
from selenium import webdriver

browser = webdriver.Ie()
browser.get('http://www.baidu.com/')

2.1.2 Headless mode startup

Headless Chrome is an interface free form of Chrome browser. You can run your program using all the features supported by chrome without opening the browser. Compared with modern browsers, headless Chrome is more convenient to test web applications, obtain screenshots of websites, do crawlers to grab information, etc. Compared with earlier phantom JS and SlimerJS, headless Chrome is closer to the browser environment.

Headless Chrome requires Chrome version:
According to the official documents, the mac and linux environments require the chrome version to be 59 +, while the windows version requires the chrome version to be 60 +, and the chrome River requires the 2.30 + version.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

chrome_options = webdriver.ChromeOptions()
# Use headless no interface browser mode
chrome_options.add_argument('--headless') //Add no interface option
chrome_options.add_argument('--disable-gpu') //If this option is not added, sometimes there will be positioning problems

# Start the browser and get the web page source code
browser = webdriver.Chrome(chrome_options=chrome_options)
mainUrl = "https://www.taobao.com/"
browser.get(mainUrl)
print(f"browser text = {browser.page_source}")
browser.quit()

2.1.3 load configuration and start browser

Selenium operating browser does not load any configuration. Here is how to load Chrome configuration:

Use the Chrome address bar to enter chrome://version/ , check your "profile path", and then call this configuration file when the browser starts. The code is as follows:
#coding=utf-8
from selenium import webdriver
option = webdriver.ChromeOptions()
option.add_argument('--user-data-dir=C:\Users\Administrator\AppData\Local\Google\Chrome\User Data') #Set to the user's own data directory
driver=webdriver.Chrome(chrome_options=option)

The method of loading Firefox configuration is somewhat different:

Open Firefox and click Settings > in the upper right corner? (help) > troubleshooting information > display folder. Open it and copy the path
# coding=utf-8
from selenium import webdriver
# Profile address
profile_directory = r'C:\Users\xxx\AppData\Roaming\Mozilla\Firefox\Profiles\1x41j9of.default'
# Load configuration
profile = webdriver.FirefoxProfile(profile_directory)
# Launch browser configuration
driver = webdriver.Firefox(profile)

2.2 element positioning

Object positioning should be the core of automatic testing. If you want to operate an object, you should first identify the object. An object is like a person, he will have various characteristics (attributes), such as we can find a person through a person's ID number, name, or where he lives in the street, floor, and door number. Then an object also has a similar attribute. We can find the object through this attribute.

webdriver provides a series of object positioning methods, including the following:

  • ID location: find_element_by_id()
  • Name: find_element_by_name()
  • Class positioning: find_element_by_class_name()
  • Link location: find_element_by_link_text()
  • partial link location: find_element_by_partial_link_text()
  • Tag positioning: find_element_by_tag_name()
  • XPath positioning: find_element_by_xpath()
  • CSS positioning: find_element_by_css_selector()
#coding=utf-8
from selenium import webdriver
browser=webdriver.Firefox()
browser.get("http://www.baidu.com")
#########Positioning method of Baidu input box##########
#Locate by id
browser.find_element_by_id("kw").send_keys("selenium")
#Locate by name
browser.find_element_by_name("wd").send_keys("selenium")
#Locate by tag name
browser.find_element_by_tag_name("input").send_keys("selenium")
#Locate by class name
browser.find_element_by_class_name("s_ipt").send_keys("selenium")
#Positioning through CSS
browser.find_element_by_css_selector("#kw").send_keys("selenium")
#Locate by xpath
browser.find_element_by_xpath("//input[@id='kw']").send_keys("selenium")
############################################
browser.find_element_by_id("su").click()
time.sleep(3)
browser.quit()

2.2.1 solutions when class contains spaces:

When actually locating elements, it is often found that class name is a composite class with multiple class combinations, separated by spaces. If an error is reported during direct positioning, it can be handled in the following ways:

  • The class attribute is unique, but there are spaces. Select the only one on both sides of the space
  • If the class es separated by spaces are not unique, they can be located by index
    self.driver.find_elements_by_class_name('table-dragColumn')[0].click()
  • Positioning through css method (space is replaced by '.)
#Add (.) Use a dot (.) To replace
self.driver.find_element_by_css_selector('.dtb-style-1.table-dragColumns').click()
#Contains the entire class
self.driver.find_element_by_css_selector('class="dtb-style-1 table-dragColumns').click()

2.3 three waiting modes of selenium

Sometimes, in order to ensure the stability of the script, the waiting time needs to be added to the script.

2.3.1 forced waiting

The first and simplest way is to forcibly wait for sleep(xx). You need to introduce the "time" module. This is called forced waiting. No matter whether your browser is loaded or not, the program has to wait for 3 seconds. Once 3 seconds arrive, continue to execute the following code. It is very useful for debugging. Sometimes you can wait in the code, but it is not recommended to always use this waiting method, It is too rigid, which seriously affects the execution speed of the program.

# -*- coding: utf-8 -*-
from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get('http://baidu.com')

time.sleep(3)  # Force a wait of 3 seconds before proceeding to the next step

print(driver.current_url)
driver.quit()

2.3.2 hidden waiting

The second method is called implicit waiting by adding implicitly_wait() method can easily realize intelligent waiting; implicitly_wait(30) should be used better than time Sleep () is more intelligent. The latter can only choose to wait for a fixed time. The former can wait intelligently within a time range.

# -*- coding: utf-8 -*-
from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(30)  # Wait implicitly for up to 30 seconds
driver.get('http://baidu.com')

print(driver.current_url)
driver.quit()

2.3.3 explicit waiting

The third method is explicit wait, WebDriverWait, which matches the until() and until() of this class_ With the not () method, you can wait flexibly according to the judgment conditions. Its main meaning is: the program takes a look every xx seconds. If the condition is true, execute the next step. Otherwise, continue to wait until the maximum time set is exceeded, and then throw TimeoutException.

The WebDriverWait class of the wait module is an explicit wait class. First look at its parameters and methods:

selenium.webdriver.support.wait.WebDriverWait (class)

1.init:

  • Driver: pass in the WebDriver instance, that is, the driver in our example above
  • Timeout: timeout, the longest waiting time (taking into account the hidden waiting time)
  • poll_frequency: call until or until_ The interval between methods in not. The default is 0.5 seconds
  • ignored_exceptions: exceptions ignored if until or until is called_ If an exception in this tuple is thrown in the process of not, the code will not be interrupted and continue to wait. If an exception outside this tuple is thrown, the code will be interrupted and an exception will be thrown. By default, there is only NoSuchElementException.

2.until:

  • Method: during the waiting period, call the incoming method at regular intervals (_init_frequency) until the return value is not False
  • Message: if timeout occurs, TimeoutException will be thrown and message will be passed in as an exception

3.until_not:

  • In contrast to until, until continues to execute when an element occurs or any condition is true,
  • until_not means that when an element disappears or any condition does not hold, the execution will continue. The parameters are the same, and will not be repeated.

2.4 browser operation

2.4.1 browser maximization and minimization

  • Maximize browser:

    browser.maximize_window()

  • Minimize browser display:

    browser.minimize_window()

2.4.2 browser setting window size

  • Set the browser width of 480 and height of 800 to display:

    browser.set_window_size(480, 800)

2.4.3 browser forward and backward

  • forward:

    browser.forword()

  • back off:

    browser.back()

2.5 operation test object

Generally speaking, the following methods are commonly used to manipulate objects in webdriver:

  1. Click -- click the object
  2. send_keys -- simulates key input on an object
  3. Clear -- clear the contents of the object, if possible
  4. Submit -- submit the contents of the object, if possible
  5. Text -- used to get the text information of the element

2.6 mouse events

Mouse events generally include right clicking, double clicking, dragging, moving the mouse over an element, and so on.
ActionChains class needs to be introduced.

Introduction method:

from selenium.webdriver.common.action_chains import ActionChains

ActionChains Common methods:
perform()  Execute all ActionChains Behavior stored in;
context_click()  Right click;
double_click()   Double click;
drag_and_drop()  Drag;
move_to_element()  Mouse over.

Double click mouse example:

#Navigate to the element you want to double-click
 qqq =driver.find_element_by_xpath("xxx") 
#Double click the anchored element 
 ActionChains(driver).double_click(qqq).perform()

Mouse drag and drop example:

#Locate the original location of the element 
element = driver.find_element_by_name("source") 
#Locate the target location to which the element is to be moved 
target = driver.find_element_by_name("target")
#Perform the move operation of the element 
ActionChains(driver).drag_and_drop(element, target).perform()

Topics: Python Java Selenium AI crawler