1.selenium实战之从txt文档读取配置信息并执行登录

前置条件:

  1.本机已搭建ECShop3.0网站

  2.在脚本目录创建了user.txt文本如下:

  

  

目的:实现从txt中读取配置文件信息,本实战中,包含url地址、用户名、密码,然后进行ESChop的登录

附上代码:

 1 # -*- coding: utf-8 -*-
 2 from selenium import webdriver
 3 from selenium.webdriver.common.by import By
 4 from selenium.webdriver.common.keys import Keys
 5 from selenium.webdriver.support.ui import Select
 6 from selenium.common.exceptions import NoSuchElementException
 7 from selenium.common.exceptions import NoAlertPresentException
 8 import unittest, time, re, codecs, os
 9 
10 # 定义函数从文本读取内容
11 def getValue(txtPath):
12    # 读取文本的路径
13    fp = codecs.open(txtPath, 'r', encoding='utf-8')
14    # 定义空列表
15    listData = []
16    for item in fp.readlines():
17        # 去掉多余的空格,并放入到列表中
18        listData.append(item.rstrip())
19    # 关闭文件
20    fp.close()
21    # 返回文本内容列表
22    return listData
23 
24 
25 class Test(unittest.TestCase):
26     def setUp(self):
27         # 初始化浏览器
28         self.driver = webdriver.Firefox()
29         # 设置全局等待时间
30         self.driver.implicitly_wait(30)
31         # 设置txt读取的路径
32         txtPath = os.getcwd() + '\user.txt'
33         # 将返回的列表赋值给自己定义的values属性,便于在用例中调用
34         self.values = getValue(txtPath)
35         # 获取到访问的url地址,从values中取
36         self.base_url = self.values[0]
37         self.verificationErrors = []
38         self.accept_next_alert = True
39 
40     
41     def test_(self):
42         driver = self.driver
43         driver.get(self.base_url)
44         # 定位用户名输入框
45         driver.find_element_by_name("username").clear()
46         # 定位用户名输入框并输入密码
47         driver.find_element_by_name("username").send_keys(self.values[1])
48         # 定位密码输入框
49         driver.find_element_by_name("password").clear()
50         # 定位密码输入框并输入密码
51         driver.find_element_by_name("password").send_keys(self.values[2])
52         # 定位登录按钮并点击
53         driver.find_element_by_css_selector("input.btn-a").click()
54     
55 
56     def tearDown(self):
57         # 退出浏览器
58         self.driver.quit()
59         self.assertEqual([], self.verificationErrors)
60 
61 if __name__ == "__main__":
62     # 执行case
63     unittest.main()
原文地址:https://www.cnblogs.com/cmnz/p/9092713.html