使用Selenium实现登陆网站并签到

This is an article that was created 388 days ago, and the information may have evolved or changed.

由于不想亲自动手打开某网站登陆然后签到,所以制作一个python脚本实现自动操作。

Selenium官网链接: https://www.selenium.dev/

官网介绍说主要用于自动化web应用程序的测试目的,但当然不限于此。无聊的基于web的管理任务也可以(也应该)自动化。

当然也表示了:What you do with that power is entirely up to you.

如标题所说,我也就想自动签到。

安装

1
pip install selenium

如果这一步出现什么问题去查看官方文档

当前日期(20230828)自动安装的版本是:selenium==4.11.2

代码

网站URL和用户密码就不贴出来了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service


# 添加option --headless 参数为不弹窗运行
options = Options()
options.add_argument('--headless')

# 4.6版本前需要指定路径,使用本地驱动
# 指定浏览器驱动路径,以Chrome为例,需要下载对应版本的ChromeDriver并指定其路径
# driver_path = 'D:/xx/xx/chromedriver.exe' # 将路径替换为实际保存的ChromeDriver的路径

# service = Service(executable_path=driver_path)
# driver = webdriver.Chrome(options=options, service=service)
# driver = webdriver.Chrome(service=service)

# 4.6版本之后使用如下代码, 当然使用上面代码指定路径也可以运行
service = Service()
driver = webdriver.Chrome(options=options, service=service)

try:
# 打开指定网站登陆页面URL
url = 'https://www.xxx.com/login.html'
driver.get(url)

# 找到用户名和密码输入框
username_input = driver.find_element(By.ID, 'user') # 根据实际情况修改用户名输入框的定位方式
password_input = driver.find_element(By.ID, 'password') # 根据实际情况修改密码输入框的定位方式

# 清空输入框
username_input.clear()
password_input.clear()

# 输入用户名和密码
username_input.send_keys('username')
password_input.send_keys('password')

# 提交登录
login_button = driver.find_element(By.LINK_TEXT, '登录') # 根据实际情况 按钮的定位方式
login_button.click() # 点击登录按钮

# 跳转到指定页面(签到页面的URL),如果签到按钮在登陆成功后跳转的页面可以跳过此步骤
qd_url = 'https://www.xxx.com/xx.html'
driver.get(qd_url)

# 在跳转后的页面找到签到按钮并点击
qd_button =driver.find_element(By.LINK_TEXT, '签到') # 根据实际情况修改签到按钮的定位方式
# qd_button = driver.find_element(By.LINK_TEXT, '退出') # 根据实际情况修改签到按钮的定位方式
qd_button.click()

# 根据网页弹出对话框确认是否完成操作,一般签到成功后都有一个弹窗,如果没有,可以定位是否有“已签到”对应的元素来判断
res_confirm = driver.find_element(By.ID, 'tt-from')
if res_confirm:
print('DONE>>>>>>')
else:
print('<<<<<<BAD')
except Exception as e:
print(e)
print('OPS,ERROR>>>>>')
finally:
# 关闭浏览器驱动
driver.quit()

注意

使用以下代码,需要本地能访问 https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json 该文件,然后访问 https://edgedl.me.gvt1.com 下载对应的 ChromeDriver

1
2
3
# 4.6版本之后使用如下代码, 当然使用上面代码指定路径也可以运行
service = Service()
driver = webdriver.Chrome(options=options, service=service)

如此说来,这种方式需要实时联网操作,对于本地内部使用不是很友好

如本地内部使用,还是去下载对应版本的 ChromeDriver

20230922 补充

网神 NSG 3600 和网神 SecSSL 3600 重置密码 信锐NMC对接华为AC实现授权ACL下发
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×