python打造自動化腳本

疫情當下,我們老師讓我們一天提交兩次溫度信息,上下午各一次。信息包括姓名,學號,溫度,日期,居住地,同居人情況等等。
對於及其懶惰的我來說,每次都得填這些信息太麻煩了。所以就寫了一個腳本,來幫助我完成,每次只需要改動需要修改的信息就行了,方便。
代碼如下:

from splinter.browser import Browser
import time
import win32api, win32con

# 驅動
driver_name = 'chrome'
"""已修改爲自動獲取,無需改動"""
# 運行的時候請自行改爲對應的相對路徑或者絕對路徑
executable_path = 'D:/Workspace/Pycharm/designer/Temperature/chromedriver.exe'  # 驅動所在的路徑


"""已修改爲自動獲取,無需改動"""
# 運行的時候請自行改爲對應的相對路徑或者絕對路徑
# CONFIG_PATH = "D:\\Workspace\\Pycharm\\designer\\Temperature\\conf.ini"  # 配置文件所在的路徑


class Temperature(object):
    def __init__(self):
        # 讀取配置信息
        config = Temperature.readconfig()

        # 前邊帶_的,其值是基本不改變的
        self._class = config['class']  # 班級
        self._name = config['name']  # 學生姓名
        self._id = config['id']  # 學號
        self._address = config['address']  # 居住地
        self._date = ""  # 日期,已設置爲系統自動獲取
        self._am_or_pm = ""  # 上午還是下午,已設置爲系統自動獲取
        self.temp = config['temp']  # 體溫
        self._phone = config['phone']  # 家庭聯繫電話(同住家人)
        self.condition = config['condition']  # 同住人身體狀況
        self.activitie = config['activitie']  # 當天活動去向

        """網址"""
        self.url = "http://huahang2020jike.mikecrm.com/I0Jtvc2"

        # 獲取日期
        self._setDate()

        # 加載驅動
        self.driver = Browser(driver_name=driver_name, executable_path=executable_path)

    def start(self):
        # 如果想要使用瀏覽器默認的大小,請註釋掉下邊的兩行
        widthResolution, heightResolution = Temperature.getResolution()  # 獲取屏幕的分辨率
        self.driver.driver.set_window_size(widthResolution, heightResolution)  # 最大化瀏覽器

        # sleep(1)
        # with Browser(driver_name=driver_name, executable_path=executable_path) as driver:
        self.driver.visit(self.url)
        try:
            print("正在提交信息,請稍後...")
            time.sleep(1)
            # 提交溫度信息
            if self._class == "B16511":
                self.driver.find_by_id('opt202610372').click()
            elif self._class == "B16512":
                self.driver.find_by_id('opt202610373').click()

            if self._am_or_pm == "上午":
                self.driver.find_by_id('opt202610374').click()
            else:
                self.driver.find_by_id('opt202610375').click()

            self.driver.find_by_xpath('//*[@id="202896043"]/div[2]/div/div/input').fill(self._name)
            self.driver.find_by_xpath('//*[@id="202896044"]/div[2]/div/div/input').fill(self._id)
            self.driver.find_by_xpath('//*[@id="202896045"]/div[2]/div/div/input').fill(self._address)
            self.driver.find_by_xpath('//*[@id="202896046"]/div[2]/div/div/div[1]/input').fill(self._date)
            self.driver.find_by_xpath('//*[@id="202896048"]/div[2]/div/div/input').fill(self.temp)
            self.driver.find_by_xpath('//*[@id="202896049"]/div[2]/div/div/input').fill(self._phone)
            self.driver.find_by_xpath('//*[@id="202896050"]/div[2]/div/div/input').fill(self.condition)
            self.driver.find_by_xpath('//*[@id="202896051"]/div[2]/div/div/input').fill(self.activitie)
            time.sleep(1)

            win32api.MessageBox(0, "請再次確認要提交的信息,無誤後手動點擊下方提交按鈕", "提醒", win32con.MB_OKCANCEL)

            # driver.find_by_id('form_submit').click()  # 設置自動提交
            print("提交信息成功")
        except Exception as exc:
            print("error:" + str(exc))

    def _setDate(self):
        self._date = time.strftime("%Y-%m-%d", time.localtime(time.time()))
        hour = int(time.strftime("%H", time.localtime(time.time())))
        if hour < 12:
            self._am_or_pm = "上午"
        elif hour >= 12:
            self._am_or_pm = "下午"
        print("當前時間:" + self._date + ", " + self._am_or_pm)

    @staticmethod
    def getResolution():
        """
        獲取屏幕的分辨率,以便最大化設置瀏覽器
            @由於我的屏幕分辨率是縮放150%,所以我最後除了1.5,在我的電腦上感覺還可以。
        """
        import winreg
        import wmi
        PATH = "SYSTEM\\ControlSet001\\Enum\\"

        m = wmi.WMI()
        # 獲取屏幕信息
        monitors = m.Win32_DesktopMonitor()

        for m in monitors:
            subPath = m.PNPDeviceID
            infoPath = PATH + subPath + "\\Device Parameters"
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, infoPath)
            # 屏幕信息按照一定的規則保存(EDID)
            value = winreg.QueryValueEx(key, "EDID")[0]
            winreg.CloseKey(key)

            # 屏幕實際尺寸
            # width, height = value[21], value[22]
            # 推薦屏幕分辨率
            widthResolution = value[56] + (value[58] >> 4) * 256
            heightResolution = value[59] + (value[61] >> 4) * 256
            # 屏幕像素密度(Pixels Per Inch)
            # widthDensity = widthResolution / (width / 2.54)
            # heightDensity = heightResolution / (height / 2.54)
        return widthResolution / 1.5, heightResolution / 1.5

    @staticmethod
    def readconfig():
        import configparser
        import os
        # 讀取配置信息
        cp = configparser.ConfigParser(allow_no_value=True)
        # file_path = os.path.dirname(os.getcwd()) + '/config/config.ini'
        # parpath = os.path.abspath('.')  # 獲取當前目錄
        # parpath = os.path.dirname(parpath)  # 獲取當前目錄的上級目錄
        # CONFIG_PATH = parpath + '\\config.ini'  # 拼接查詢對應目錄
        # 上面三個可以合成這一個
        CONFIG_PATH = os.path.abspath('.') + '\\conf.ini'

        # 自動獲取驅動的路徑
        global executable_path
        executable_path = os.path.abspath('.') + '\\chromedriver.exe'

        print(executable_path)
        # 讀取配置文件(此處是utf-8-sig,而不是utf-8),這裏主要解決讀取配置文件中文亂碼問題
        cp.read(CONFIG_PATH, encoding="utf-8-sig")
        return cp['CONFIG']


if __name__ == '__main__':
    temperature = Temperature()
    temperature.start()


如果覺得驅動和你自己機器上的版本不對應,可以訪問鏈接下載對應的版本。
Splinter官網API鏈接:https://splinter.readthedocs.io/en/latest/index.html
完整的項目請點擊鏈接下載,提取碼:364f
在這裏插入圖片描述

發佈了30 篇原創文章 · 獲贊 14 · 訪問量 1821
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章