1.首先需要安装chromiun浏览器:
1.sudo yum install chromium
2.sudo apt-get install chromium-browser
以上两个命令根据linux的版本选择使用
查看版本号: chromium-browser --version
安装完成即可,一般情况下不需要配置环境变量
2.配置python环境
(1)安装python3:
sudo yum install python3
sudo yum install python3-pip
查看版本号 :python3 --version
3.下载对应版本的驱动并移动到 bin目录下
下载地址:https://chromedriver.chromium.org/downloads
移动命令
sudo mv /path/to/chromedriver /usr/bin/
同时给文件增加可执行权限:
chmod +x /path/to/chromedriver
查看版本号: chromdriver --version
4. 安装所需要的python包
sudo pip3 install selenium
sudo pip3 install flask
sudo pip3 install requests
5.准备selenium代码:
# coding:utf-8
import time
from selenium import webdriver
import sys
def run(url,account,password):
sys.path.append("/usr/bin/ptyhon3")
chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = "/usr/bin/chromium-browser"
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('blink-settings=imagesEnabled=false')
driver = webdriver.Chrome(chrome_options=chrome_options,executable_path='/usr/bin/chromedriver')
driver.implicitly_wait(60)
num= 2
c = "null"
while(num<3):
driver.get(url)
time.sleep(3)
print("开始第%s次获取"%str(num-1))
if driver.title == "登录页面":
print("进入登录")
try:
driver.find_element_by_id("loginByPassword").click()
time.sleep(1)
driver.find_element_by_id("username").send_keys(account)
driver.find_element_by_id("password").send_keys(password)
driver.find_element_by_id("authorityLoginBtn").click()
time.sleep(2)
except:
print("未登录")
cookie = driver.get_cookies()
c = cookie[1]["name"]+"="+cookie[1]["value"]+";"+cookie[0]["name"]+"="+cookie[0]["value"]
if "sid" in c:
num =4
else:
num+=1
print("cookie不正确,正在重新获取")
try:
driver.refresh()
driver.get(url)
time.sleep(3)
driver.find_element_by_id("loginByPassword").click()
time.sleep(1)
driver.find_element_by_id("username").send_keys(account)
driver.find_element_by_id("password").send_keys(password)
driver.find_element_by_id("authorityLoginBtn").click()
time.sleep(2)
except:
print("重试登录未完成,直接获取cookie")
cookie = driver.get_cookies()
c = cookie[1]["name"] + "=" + cookie[1]["value"] + ";" + cookie[0]["name"] + "=" + cookie[0]["value"]
print(c)
else:
print("cookie获取失败")
num+=1
driver.close()
driver.quit()
return c
6.使用flask 编写请求代码:
from flask import Flask, request, render_template, redirect
import getCookie
app = Flask(__name__)
# 通过ui自动化登录系统
@app.route('/getCookie', methods=['GET'])
def getCookie_data():
# 参数
url = request.args.get('url')
account = request.args.get('account')
password = request.args.get('password')
c = getCookie.run(url,account,password)
return c
if __name__ == '__main__':
# app.run(debug=True,port=32760)
# 使用0000 代表可以其他主机可以使用ip进行访问
app.run(debug=True,host ="0.0.0.0")
7.调试请求接口
使用postman调用成功: