主要目标
网页需要每五分钟手动点击确认弹窗,为实现自动化点击以写此代码。
环境需求
本代码采用的Chrome浏览器。
采用selenium,将对应Chrome版本的selenium.exe安装入python目录下。
如无法运行可以在python终端输入:pip install selenium
大体流程
本项目先有一个跳转页面A,在A点击确认跳转后进入输入账号以及密码的页面B,在B输入对应账号以及密码后点击登录即可(无验证码)进入学习页面。由于保存了cookie,直接跳转到学习视频页面即可刷时长。
代码实现
from selenium.webdriver import Chrome #导入Chrome
from selenium.webdriver.common.by import By #根据路径寻找元素
from selenium.webdriver.common.keys import Keys #实现输入以及点击功能
from selenium.webdriver.chrome.options import Options #设置浏览器
import time #时间函数
from selenium import webdriver
username='' #用户账号
userpass='' #密码
url='http://xxxxx' #第一次出现的跳转页面的网址
option =Options()
option.add_experimental_option("detach", True) #selenium打开的浏览器如何在程序结束时不退出
web=webdriver.Chrome(options=option)
web.get(url) #打开网页
web.find_element(By.XPATH,'//*[@id="web_login"]/div/div[2]/input').click() #在A页面寻找需要点击的按钮
web.find_element(By.XPATH,'//*[@id="username"]').send_keys(username,Keys.ENTER) #在B页面寻找账号输入框并输入账号
web.find_element(By.XPATH,'//*[@id="password"]').send_keys(userpass,Keys.ENTER) #在B页面寻找密码输入框并输入密码顺便跳转
url2='http:xxxxx'
web.get(url2) #跳转对应视频页面
counter=0 #每5分钟记录一次
while (True):
print(f"已经学习{counter}分钟")
time.sleep(305)
try:
web.switch_to.alert.accept() #点击弹窗框的确认选项
except:
time.sleep(10)
web.switch_to.alert.accept() #防止页面卡顿,弹出框较慢。
counter=counter+5