使用seleium+python模拟登陆鉴权网页

先上代码:

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
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

chrome_path = r'/usr/local/bin/chromedriver' #这里是chromedriver的安装路径


def login_buc(username, password, login_url):
# driver = webdriver.PhantomJS()
chrome_options = Options()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options)
driver.get(login_url)
driver.refresh()
print(driver.title)

driver.find_element_by_name('domainAccount').send_keys(username) # 输入用户名
driver.find_element_by_name('password').send_keys(password) # 输入密码

driver.execute_script('document.getElementsByClassName("kuma-button kuma-button-primary sso-btn-submit kuma-button-lg")[0].click()') # 点击登录
# 多账号场景
try:
driver.execute_script('document.getElementsByClassName("kuma-button kuma-button-primary")[0].click()')
except Exception as e :
print("ERROR:", e)
time.sleep(5)
driver.get(login_url)
time.sleep(5)
print("===>",driver.title)
driver.close()


# 测试
if __name__ == '__main__':
login_buc('登陆账号', '登陆密码', '目标网址')

我这里的selenium使用的是最新的3.141.0版本,这里要注意一下,selenium早就已经放弃PhantomJS了,建议使用firefox或者chrome,我这里在本地安装一个chromedriver。由于这个机器是苹果mac,就需要在终端里输入brew install --cask chromedriver即可安装,然后等待安装完毕之后,使用which chromedriver来获取chromedriver的安装路径,如图:

然后在脚本里体现出来就行,即脚本里的chrome_path,不然执行后会爆Message: 'chromedriver' executable needs to be in PATH.这个错误。上述脚本执行效果如下:

如果执行出现了NoSuchElementException: Unable to locate element这个错误,建议适度调大time.sleep的时间,因为开启页面后,并不是元素都一次性加载完成的,客观依赖于网速和电脑。

感谢您请我喝咖啡~O(∩_∩)O,如果要联系请直接发我邮箱chenx1242@163.com,我会回复你的
-------------本文结束感谢您的阅读-------------