python3.7,Chrome或者Edeg瀏覽器,Chrome驅(qū)動或者Edge驅(qū)動
創(chuàng)新互聯(lián)建站是一家專注于成都網(wǎng)站設計、網(wǎng)站建設與策劃設計,東昌網(wǎng)站建設哪家好?創(chuàng)新互聯(lián)建站做網(wǎng)站,專注于網(wǎng)站建設10余年,網(wǎng)設計領(lǐng)域的專業(yè)建站公司;建站業(yè)務涵蓋:東昌等地區(qū)。東昌做網(wǎng)站價格咨詢:18980820575
#需要配置selenium庫,ddddocr庫,pillow庫,在終端執(zhí)行以下命令
pip install selenium
pip install pillow
pip install ddddocr
1.模擬登錄說唱大學微服務,需要ddddocr模型識別驗證碼(免費獲?。?/p>
2.虛擬位置信息填寫,注釋:其余信息保留上一天信息
3.反饋打卡信息到QQ郵箱,注釋:需要自行配置POP3/ SMTP服務
4.掛到騰訊云服務上,每天定時自動打卡
QQ郵箱配置鏈接
騰訊云服務器上運行(免費1個月)選擇輕量應用服務器,我選的linux系統(tǒng),這里的實例也是linux
參考騰訊文檔,遠程登錄linux實例
1.以root登錄
2.下載Python3.7,升級pip,yum,更換國內(nèi)源
3.安裝庫,執(zhí)行以下命令
pip3 install selenium
pip3 install pillow
pip3 install ddddocr
4.在linux上安裝谷歌瀏覽器和驅(qū)動
在目錄 /etc/yum.repos.d/ 下新建文件 google-chrome.repo
cd /etc/yum.repos.d/
vim google-chrome.repo
vim命名編輯google-chrome.repo文件,輸入如下內(nèi)容:
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/$basearch
enabled=1
gpgcheck=1
gpgkey=https://dl-ssl.google.com/linux/linux_signing_key.pub
具體操作:按i插入,按Esc,然后輸入:,再輸入wq,然后按Enter退出
安裝瀏覽器,依次輸入以下命令
yum -y install google-chrome-stable --nogpgcheck
# 檢查版本信息
google-chrome --version
# 找到google_chrome路徑:我對應的路徑是/usr/bin/google-chrome,輸入路徑創(chuàng)建軟連接
which google-chrome
# 創(chuàng)建軟連接
ln -s /usr/bin/google-chrome /bin/chrome
# 安裝驅(qū)動
wget https://npm.taobao.org/mirrors/chromedriver/88.0.4324.96/chromedriver_linux64.zip
# 解壓
yum -y install zip
unzip chromedriver_linux64.zip
# 轉(zhuǎn)移chromedriver到/user/bin目錄下
sudo mv chromedriver /usr/bin
# 解決root運行chrome問題
vim /opt/google/chrome/google-chrome
# 將最后一行改為如下:
exec -a "$0" "$HERE/chrome" "$@" --no-sandbox $HOME
將Python自動運行程序?qū)懙絣inux里:
vim automatic.py
# 然后把程序復制進去
測試運行:
python3 automatic.py
利用crontab定時運行python腳本:(輸入如下命令)
crontab -e
# 從左到右依次表示分、時、日、月、周,設置為每天0:01自動打卡
1 0 * * * /usr/bin/python3 /root/automatic.py
# 啟動服務
service crond restart
有詳細解釋,在windows和centos7均可運行
# -*- coding: utf-8 -*-
"""
@Time : 2022/7/11
@Author : PC
@File : daka
@Description :
"""
import sys
"這里填寫linux的python包依賴路徑"
sys.path += ['/usr/local/lib/python3.6/site-packages/', '/usr/local/lib64/python3.6/site-packages/']
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import ddddocr
"""獲取driver"""
def driver(driverpath):
chrome_options = webdriver.ChromeOptions()
# 設置無界面顯示參數(shù),因為要放在linux服務器上運行,無法顯示界面,調(diào)試的時候需要把下面五行注釋掉,顯示chrome界面
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('window-size=1920x1080')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--hide-scrollbars')
chrome_options.add_argument('--headless')
browser = webdriver.Chrome(executable_path=driverpath, options=chrome_options) # 加載 chromedriver,用edge的就去下載edgedriver
return browser
"""
驗證碼識別
"""
def ocr(path):
ocr = ddddocr.DdddOcr()
with open(path, 'rb') as f:
img_bytes = f.read()
res = ocr.classification(img_bytes) # numpy版本報錯不影響,不要升級
return res
"""
更改chrome定位
"""
def setloca(browser, lat, long):
browser.execute_cdp_cmd(
"Browser.grantPermissions", # 授權(quán)地理位置信息
{
"origin": "https://wfw.scu.edu.cn/",
"permissions": ["geolocation"]
},
)
browser.execute_cdp_cmd(
"Emulation.setGeolocationOverride", # 虛擬位置
{
"latitude": lat,
"longitude": long,
"accuracy": 50,
},
)
try: # 提交位置信息
area_element = WebDriverWait(browser, 10).until(
EC.element_to_be_clickable((By.NAME, 'area'))
)
area_element.click()
except Exception as error:
print('get location wrong :\n', error)
time.sleep(2) # 等待位置信息
"""
郵箱信息,沒有單獨寫個函數(shù),需要配置QQ郵箱,開啟POP3/ SMTP服務,并獲取授權(quán)碼
因為是提醒自己打卡,所以自己是發(fā)件人,自己是收件人
填入授權(quán)碼
"""
def stamp(userstamp, flag):
# 建立郵箱信息
my_sender = 'xxxx@qq.com' # 發(fā)件人郵箱賬號
my_pass = 'xxxx' # 發(fā)件人郵箱密碼(當時申請smtp給的口令)
my_user = userstamp # 收件人郵箱賬號
if flag:
msg = MIMEText('恭喜您今天打卡成功', 'plain', 'utf-8')
msg['From'] = formataddr(["打卡代理", my_sender]) # 括號里的對應發(fā)件人郵箱昵稱、發(fā)件人郵箱賬號
msg['To'] = formataddr(["打卡用戶", my_user]) # 括號里的對應收件人郵箱昵稱、收件人郵箱賬號
msg['Subject'] = "打卡提示" # 郵件的主題,也可以說是標題
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 發(fā)件人郵箱中的SMTP服務器,端口是465
server.login(my_sender, my_pass) # 括號中對應的是發(fā)件人郵箱賬號、郵箱密碼
server.sendmail(my_sender, [my_user, ],
msg.as_string()) # 括號中對應的是發(fā)件人郵箱賬號、收件人郵箱賬號、發(fā)送郵件
server.quit() # 關(guān)閉連接
else:
msg = MIMEText('打卡失敗,請手動打卡', 'plain', 'utf-8')
msg['From'] = formataddr(["打卡代理", my_sender])
msg['To'] = formataddr(["打卡用戶", my_user])
msg['Subject'] = "打卡提示"
server = smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(my_sender, my_pass)
server.sendmail(my_sender, [my_user, ], msg.as_string())
server.quit()
"""
打卡程序主體
"""
def clock(username, password, url, lat, long, userstamp, browser):
browser.delete_all_cookies() # 清空cookie
browser.get(url)
attempt = 0
while True:
try: # 切換為賬號密碼登錄
browser.switch_to.frame('loginIframe') # 切換frame
switch_element = WebDriverWait(browser, 10).until(
EC.element_to_be_clickable((By.XPATH,
'/html/body/div/div/div[2]/div[2]/div[1]/div/div[3]'))
) # 找到對應元素位置
switch_element.click() # 點擊切換
except Exception as error:
print('network wrong :\n', error)
# 輸入賬號和密碼
input_user = browser.find_element(by=By.XPATH,
value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[1]/div[2]/div/input')
input_user.send_keys(username)
input_pwd = browser.find_element(by=By.XPATH,
value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[2]/div[2]/div/input')
input_pwd.send_keys(password)
time.sleep(0.5)
ver_btn = browser.find_element(by=By.CLASS_NAME, value='van-field__button')
ver_btn.click() # 刷新驗證碼
time.sleep(2)
# 獲取圖片元素的位置
loc = ver_btn.location
# 獲取圖片的寬高
size = ver_btn.size
# 獲取驗證碼上下左右的位置
left = loc['x']
top = loc['y']
right = (loc['x'] + size['width'])
botom = (loc['y'] + size['height'])
val = (left, top, right, botom)
# 驗證碼截圖保存到當前目錄下code.png
# 打開網(wǎng)頁截圖
browser.save_screenshot('full.png')
# 通過上下左右的值,去截取驗證碼
pic = Image.open('full.png')
ver_pic = pic.crop(val)
ver_pic.save('code.png')
verification = ocr('code.png')
print('current verification code:' + verification)
input_ver = browser.find_element(by=By.XPATH,
value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/div[3]/div[2]/div/input')
input_ver.send_keys(verification)
browser.find_element(by=By.XPATH,
value='/html/body/div/div/div[2]/div[2]/div[2]/div[3]/button').click() # 點擊登錄
time.sleep(5) # 等待跳轉(zhuǎn)
if browser.current_url == url: # 檢驗登錄成功
try:
browser.find_element(by=By.XPATH,
value='/html/body/div[2]/div/div[2]/div').click()
time.sleep(0.5)
except:
break
break # 登錄成功,退出循環(huán)
attempt += 1
if attempt == 10: # 有時候網(wǎng)頁會卡,即使密碼正確也登錄不上去,每次循環(huán)嘗試5次登錄(一般5次內(nèi)能登錄上去)
print('please check your usernumber and password, or try later')
browser.quit()
sys.exit()
setloca(browser, lat, long) # 設置地理位置
browser.find_element(by=By.XPATH,
value='/html/body/div[1]/div/div/section/div[5]/div/a').click() # 提交信息
try:
ok_element = WebDriverWait(browser, 5).until(
EC.element_to_be_clickable(
(By.XPATH, '/html/body/div[5]/div/div[2]/div[2]')) # 提交按鈕
)
ok_element.click()
print(username, 'success clock')
WebDriverWait(browser, 5).until(
EC.presence_of_element_located(
(By.XPATH, '/html/body/div[5]/div/div[1]')) # 成功對話框標題
)
title_success = browser.find_element(by=By.XPATH,
value='/html/body/div[5]/div/div[1]').get_attribute("innerHTML")
print('message from website:', title_success)
flag = True
stamp(userstamp, flag)
except:
info = browser.find_element(by=By.CLASS_NAME,
value='wapat-title').get_attribute('innerHTML')
print('message from website:', username, ':', info)
flag = False
stamp(userstamp, flag)
browser.quit()
if __name__ == '__main__':
# driverpath = '..\chromedriver\chromedriver.exe' # chromedriver路徑 windows下
driverpath = '/usr/chrome/chromedriver/chromedriver' # linux下
url = 'https://wfw.scu.edu.cn/ncov/wap/default/index' # 已經(jīng)登錄進去的界面地址
username = ['xxxxx', 'xxxxx'] # 用戶名(學號)
password = ['xxxxx', 'xxxxx'] # 密碼
latitude = 30. # 虛擬位置緯度
longitude = 104.0 # 經(jīng)度
userstamp = ['xxxx@qq.com', 'xxxx@qq.com']
for i in range(2):
try:
browser = driver(driverpath)
except:
print('please update your browser driver')
clock(username=username[i], password=password[i], lat=latitude, long=longitude, url=url, userstamp=userstamp[i], browser=browser)
運行結(jié)果圖: