Python利用Selenium实现自动化验证登录

Python里面使用Selenium是一个很重要的自动化测试模块,我们可以用它写一个验证登录脚本,有了这个可以用来保存cookie信息等,下面是一个简单的demo:

from selenium import webdriver
from selenium.webdriver.common.by import By #用于定位class元素
from selenium.webdriver.support.ui import WebDriverWait #等待
from selenium.webdriver.support import expected_conditions as EC #执行条件
import time
#我们可以把账号密码放在txt文件中,用||分隔
with open(filename.txt,'r') as f:
	account=f.read().split('||')

name=account[0]
password=account[1]
#1.创建浏览器对象
options=webdriver.EdgeOptions()
options.headless=True#无头浏模式
#以下设置可以将模拟浏览器伪装成自己常用的浏览器
prefs={'profile.default_content_settings_popups':0}
options.add_experimental_option('prefs',prefs)
options.add_argument(r"--user-data-dir=D:\Users\zhangsanlisi\AppData\Local\Microsoft\Edge\User Data copy") # 设置成用户自己的数据目录,这里有个坑,需要把自己的浏览器用户目录的东西复制一份改个名字设置到这里引用,否则会报错
web =webdriver.Edge(options=options)
html=web.get('https://xxxx.sod.com/sse/login')
WebDriverWait(web, 10).until(EC.presence_of_element_located((By.XPATH, "//div//input[@id='username']")) #获取带有input标签,并给与网页最大10秒的加载时间
).clear()
WebDriverWait(web, 10).until(EC.presence_of_element_located((By.XPATH, "//div//input[@id='username']")) #获
).send_keys(name)
WebDriverWait(web, 10).until(EC.presence_of_element_located((By.XPATH, "//div//input[@id='password']")) 
).clear()
WebDriverWait(web, 10).until(EC.presence_of_element_located((By.XPATH, "//div//input[@id='password']")) 
).send_keys(password)
WebDriverWait(web, 10).until(EC.presence_of_element_located((By.XPATH, "//div//input[@id='formsubmitButton']")) 
).click()
time.sleep(5)
#2.打开网址
web.get('http://xxxx.ewdt.com/')
#把获取到的cookie连接起来保存备用
cookie='; '.join([(i['name']+'='+i['value']) for i in  web.get_cookies()])
with open('cookie.txt','w') as f:
   f.write(cookie)
web.close()
print('cookie已更新')

你可能感兴趣的:(自动化,python,selenium,自动化)