python模擬網頁輸入與按鈕點選——東南大學一鍵健康上報

2021-03-10 12:00:48


一、環境安裝

安裝selenium : 在終端輸入: pip install selenium
下載chromedriver :[ [http://chromedriver.storage.googleapis.com/index.html]]下載 (與安裝的chrome瀏覽器版本一致)。解壓後放在python.exe同目錄下。

二、範例

1.XPath獲取

例如使用chrome瀏覽器:
右鍵點選輸入框或按鈕,點選「檢查」:
如圖:
在這裡插入圖片描述
右鍵點選相應的元素,點選複製完整的XPath路徑:
在這裡插入圖片描述
獲取的XPath在之後程式碼中使用。

2.程式碼實現

程式碼如下:

#coding=utf-8
#####seu一鍵上報體溫####
#######作者Gulzar######
from selenium import webdriver
import time
import re
import random
import sys
temp=random.uniform(35,37)#隨機生成體溫
str_temp=str(temp)
print(str_temp)
opt = webdriver.ChromeOptions()#建立瀏覽器
opt.set_headless()#無視窗模式
driver = webdriver.Chrome(options=opt)#建立瀏覽器物件
print("The browser has been opened.")
driver.get('http://ehall.seu.edu.cn/qljfwapp2/sys/lwReportEpidemicSeu/index.do?t_s=1615173794065&amp_sec_version_=1&gid_=ZCtaN3VqbnlHQVlIUmNBRG5qN29YV1ZLWU9LY21lN0NRbG1qYndqRkRGTUlwQUV4aWpza3RIQ1Fzb3F6eUhYY1NOdzNiTjFEVC8zekEyQ3dXR0U3RWc9PQ&EMAP_LANG=zh&THEME=indigo#/dailyReport')#開啟網頁
#driver.maximize_window()#最大化視窗
time.sleep(1)#載入等待
driver.find_element_by_id('username').send_keys("*******") #賬號
driver.find_element_by_id('password').send_keys("*******") #密碼
driver.find_element_by_xpath("//button[@class='auth_login_btn primary full_width'][@type='submit']").click()#點選按鈕
print("Login in completed.")
time.sleep(2)
try:
    driver.find_element_by_xpath("/html/body/main/article/section/div[2]/div[1]").click()
    time.sleep(2)
    driver.find_element_by_xpath("/html/body/div[11]/div/div[1]/section/div[2]/div/div[4]/div[2]/div[1]/div[1]/div/input").send_keys(str_temp)
    driver.find_element_by_xpath("//*[@id='save']").click()
    print("Data has been saved.")
    time.sleep(2)
    driver.find_element_by_xpath("/html/body/div[60]/div[1]/div[1]/div[2]/div[2]/a[1]").click()
    print("Mission complete!")
    time.sleep(1)
except:
    print("Exception occured. Maybe you have already uploaded your health data.")
finally:
    driver.close()
    sys.exit()

用XPath查詢到對應的按鈕或輸入框之後,使用send_keys()函數輸入,click()函數點選按鈕,按正常的使用流程即可實現自動上報。


總結

可以在控制面板的管理工具介面建立計劃任務,之後只需要開著電腦就可以實現每天自動上傳體溫了。