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調用成功:
image.png