前提:公司的路由器密码忘记了,试了好多个没对,懒得手动测试,然后想试试python+selenium的网页自动操作功能,参考了某大神的教程,结果如下:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
url = 'http://192.168.xx.1/webpages/login.html' #配置测试地址
wd = webdriver.Chrome() #调用chrome,这里将chromedriver.exe放入python目录中,不用路径调用
wd.get(url)
f = open(r'e:/passwd1.txt') #配置密码文件路径
for i in f.readlines():
time.sleep(1) #等待页面刷新
input_account = wd.find_element(By.ID,'username')
input_account.send_keys('admin') #使用固定用户admin
i = i.strip('n')
input_password = wd.find_element(By.XPATH,'//*[@type="password"]')
input_password.send_keys(i)
login_button = wd.find_element(By.ID,'login-btn')
login_button.click()
print(i)
time.sleep(0.1) #等待结果
if(wd.find_element(By.XPATH,'//div//h3')):
# 这里需要一个登陆错误判定,密码错误时,出现h3提示
wd.refresh()
过程问题:
1,使用最新版的selenium,指令格式应为wd.find_element(By.ID,'xxx'),网上很多教程都是旧的,指令格式为wd.find_element_by_ID('xxx'),执行报错,改格式后正常;
2,使用ID查找元素,用户名输入框、登陆按键都可以查找到,但使用ID查询password时,一直报错,问题在于网页登陆中,ID=password为加密后密码,并不是实际密码输入框内容,且内容为隐藏,重新定位密码输入框,,只能通过XPath来定位元素,使用'//*[@type="password"]'
3,接下来跑起来正常了,但测试过程中几次中断,查找原因,为页面加载没那么快,第二次循环查找不到username,加入time.sleep(1)等待,运行正常



