selenium3 and Python3 actual web automated testing framework
First, set up the environment
1, selenium environment to build
Client:
- pycharm
- python3.6
Driver:
- Chrome → ChromeDriver
- Firefox → FirefoxDriver
- IE → InternetExplorerDriver
Selenium
1.1, Selenium installation
pip install selenium # installation
from selenium import webdriver # import
driver = webdriver.Chrome () # start the Google browser
driver.get ( "http://www.baidu.com") # Open Baidu URL
# Note: Start Google Chrome the former needs to configure Google browser middleware, downloaded from the internet chromedriver.exe , place it in python under the installation directory
1.2, use scripts to start different browsers
Before starting the browser to be configured browser corresponds to driver:
- Chrome --chromedriver.exe: Google browser plug-in debugging drivers
- Firefox --geckodrive.exe: Firefox browser plug-in debugging drivers
- IE --MicrosoftWebDriver.exe: IE browser debugging plug drive
The above three exe file is placed under the directory after downloading python
1) Start Google Chrome
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.baidu.com')
2) Start Firefox:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.baidu.com')
3) Start IE browser
from selenium import webdriver
driver = webdriver.Ie()
# Driver = webdriver.Edge () # win 10 version of the boot IE browser, this line of code
driver.get('http://www.baidu.com')
2, title_contains page title under judge whether the use expected_condition consistent with what we want, such as the page title to determine whether there is 'registered' words:
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
import time
driver = webdriver.Chrome()
# Driver = webdriver.Edge () # win 10 version of the boot IE browser, this line of code
driver.get('http://www.5itest.cn/register')
time.sleep(5)
is_live = expected_conditions.title_contains ( ' registration ') # Is there a word registered in the title page judgment
print('is_live:',is_live)
Return result:
is_live: <selenium.webdriver.support.expected_conditions.title_contains object at 0x000000000354DEF0> # 存在
3, positioned in different ways
Access the registration link: http://www.5itest.cn/register, testing
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.5itest.cn/register')
driver.find_element_by_id ( 'register_email'). send_keys ( "[email protected]") # fill in the mailbox
user_name_node = driver.find_elements_by_class_name ( 'controls') [1] # use classname defined, requires careful handling
user_name_node.find_element_by_class_name ( 'form-control') . send_keys ( 'Eric_nan') # fill in the username
driver.find_element_by_name ( 'password'). send_keys ( '111111') # fill in password
driver.find_element_by_xpath ( '// * [@ id = "captcha_code"]'). send_keys ( '2222') # fill codes
Script Control to launch a browser and access the registration page, and automatically enter a set value:
4, using the determined elements are visible expected_conditions
from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
locator = (By.CLASS_NAME, 'controls' ) # by classname find ways controls
WebDriverWait(driver,1).until(expected_conditions.visibility_of_element_located(locator))
WebDriverWait # : two arguments, one is Driver , is another timeout (int type )
Visibility_of_element_located # : only to find the corresponding element in the visible elements in. If the return memory address
5, how to solve the verification code is automatically entered
1) The registration page full-screen theme stored (using driver.save_screenhot method), then the partial region codes saved screenshot
Open the local picture, part of the interception area need to use PIL, installation: pip install -i
base_dir = os.path.dirname (os.path.dirname (os.path.abspath ( __ file__))) # The first path project
image_path = os.path.join (base_dir, 'Image ', 'imooc.png') # image path, a full-screen image after storage screenshot
code_path = os.path.join (base_dir, 'Image ', 'code.png') # CAPTCHA save path
driver.get('http://www.5itest.cn/register')
driver.save_screenshot (image_path) # Full screen capture
code_element = driver.find_element_by_id ( "getcode_num") # target character codes where
# Print (code_element.location) # get the element ( picture ) the upper left corner (x, y) coordinates
# Print (code_element.size) # obtains the element ( image ) length, width
left_x = code_element.location [ 'x'] # the upper left corner x value
top_y = code_element.location [ 'y'] # left corner y value
right_x = left_x + code_element.size['width'] # 右下角x值
right_y = top_y + code_element.size['height'] # 右下角y值
im = Image.open (image_path) # use PIL under the Image Open the downloaded imooc.png picture
img = im.crop ((left_x, top_y , right_x, right_y)) # specified a cut out portion
img.save(code_path) # 保存
2) Use showapiRequest solve image verification code recognition
①, using pytesseract have problems identifying the picture
Installation: PIP install pytesseract
import pytesseract
from PIL import Image
image = Image.open("E:/imooc2.png")
text = pytesseract.image_to_string (image) # convert the picture into a text string
print(text)
# Disadvantages: mechanical reading, can not read the picture irregular fonts, not suitable for interfering relatively strong reading the CAPTCHA text
Select: codes identifying alphanumeric _ file, find the requested example, download the SDK: ShowapiRequest.py
The ShowapiRequest.py file into the project, the new read_code_img.py file for reading picture verification code:
Security Code:
from setting.ShowapiRequest import ShowapiRequest
from setting import setting
r = ShowapiRequest("http://route.showapi.com/184-4","62666","d61950be50dfgjnr9969f741b8e730f5" )
# ShowapiRequest The first parameter is the World Wide Web easily source web url , the second argument is easy to source your own online appId , the third parameter is the key easy to source online
r.addBodyPara ( "typeId", "35") #typeId : represents a number identifying several authentication code; 35 : '3' represents alphanumeric codes binding, '5' represents a 5 -digit code; 31 : digit verification code
r.addBodyPara("convert_to_jpg", "0")
r.addFilePara ( "image", setting.code_path) # add code to identify pictures
res = r.post()
print(res.text) # {"showapi_res_error":"","showapi_res_id":"6f0e4cdb977141b293ea12178ad3d37e","showapi_res_code":0,"showapi_res_body":{"Id":"5bac83cc-5637-4e2d-bc91-25a78b527241","Result":"ANLZZ","ret_code":0}}
text = res.json () [ 'showapi_res_body '] [ 'Result'] # in json read format: showapi_res_body the Result values
print (text) # return information: ANLZZ ( correctly identified )
Note: In this manner a relatively high recognition accuracy
The relevant code register encapsulated - Initial Package
Automatic registration information corresponding to the input
6, the package method of reading the configuration file
New int profile:
# localElement.ini file
[RegisterElement]
user_email=id>register_email
user_email_error=id>register_email-error
user_name=id>register_nickname
user_name_error=id>register_nickname-error
password=id>register_password
password_error=id>register_password-error
code_image=id>getcode_num
code_text=id>captcha_code
code_text_error=id>captcha_code-error
register_button=id>register-btn
Use python3 comes configparser module that reads the profile information:
from setting.setting import config_ini_dir
import configparser
class Read_Ini (object): # initialize
def __init__(self,node = None):
if node:
self.node = node
else:
self.node = 'RegisterElement' # a node configuration file
self.cf = self.load_ini ()
def load_ini (self): # load file
cf = configparser.ConfigParser () # use configparser module reads profile information
cf.read (config_ini_dir) # where the path to the configuration file
return cf
def get_value (self, key): # get the configuration file key in the value value
data = self.cf.get(self.node,key)
return data
# if __name__ == '__main__':
# read_init = Read_Ini()
# print(read_init.get_value('user_name')) # 结果:id>register_nickname
7, the package positioning element class
# find_element.py
from util.read_ini import Read_Ini
class FindElement(object):
def __init__(self,driver):
self.driver = driver
def get_element(self,key):
read_ini = Read_Ini ()
data = read_ini.get_value(key)
by,value = data.split('>')
try:
if by == 'id':
return self.driver.find_element_by_id(value)
elif by == 'name':
return self.driver.find_element_by_name(value)
elif by == 'className':
return self.driver.find_element_by_class_name(value)
elif by == 'xpath':
return self.driver.find_element_by_xpath(value)
else:
return self.driver.find_element_by_css(value)
except Exception as e:
print ( "find_element error message: ", E)
return None
* Complete Registration Process
1, the configuration file
1) LocalElement.ini: positioning element information stored
LocalElement.ini
2)setting.py:
setting.py
3) read_ini.py: reads the configuration information of the configuration file LocalElement.py
read_ini.py
4) find_element.py: acquiring location information elements
find_element.py
5) register_function.py: Registration main test
register_function.py