Python + selenium + crontab實現每日定時自動打卡

前言

近幾日迫於被輔導員三番五次的提醒每日一報打卡,就想着去寫個腳本掛在服務器上定時執行。經過我不懈的努力,最終選擇了seleniumselenium,因爲簡單(

步驟

安裝selenium庫

$ sudo pip install selenium

安裝chromdriver

因爲我有代理所以直接在官網下載的,那這裏你可以選擇用淘寶鏡像源
在這裏插入圖片描述
這裏爲了方便,我直接放命令了。Chromedriver版本我這裏選擇的是80.0.3987.16(注意要和一會兒下載的Chrome版本一致)。

  • 下載
$ wget https://npm.taobao.org/mirrors/chromedriver/80.0.3987.16/chromedriver_linux64.zip
  • 解壓
$ unzip chromedriver_linux64.zip -d . 
  • 放到相應目錄並授予可執行權限
$ sudo cp chromedriver /usr/bin && sudo chmod +x /usr/bin/chromedriver

安裝Chrome

  • 安裝依賴
$ sudo apt-get install libxss1 libappindicator1 libindicator7
  • 安裝Chrome
$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
$ sudo dpkg -i google-chrome*.deb
$ sudo apt-get install -f
  • 查看版本
$ google-chrome --version
  • 測試調試
$ google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu

編寫腳本

  • 創建腳本並授予權限
$ touch dailyReport.py && touch dailyReport.log && sudo chmod +x dailyReport.py
  • 內容
# encoding=utf8
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time


class DailyReport(object):
    def __init__(self):
        self.chrome_options = webdriver.ChromeOptions()
        # 更加高效,根據需要
        prefs = {"profile.managed_default_content_settings.images": 2,
                 "profile.default_content_setting_values.notifications": 2,
                 "profile.managed_default_content_settings.stylesheets": 2,
                 # "profile.managed_default_content_settings.cookies": 2,
                 "profile.managed_default_content_settings.javascript": 1,
                 "profile.managed_default_content_settings.plugins": 1,
                 "profile.managed_default_content_settings.popups": 2,
                 "profile.managed_default_content_settings.geolocation": 2,
                 "profile.managed_default_content_settings.media_stream": 2,
                 }
        self.chrome_options.add_experimental_option("prefs", prefs)
        self.chrome_options.add_argument('--headless') # 如果沒有圖形化界面就加上這個參數
        self.chrome_options.add_argument('--disable-gpu') # 看到知乎上有個文章說是防止bug
        self.chrome_options.add_argument('--no-sandbox')  # 這個配置很重要,代表最高權限運行
        # 不加載圖片, 提升速度
        self.chrome_options.add_argument('blink-settings=imagesEnabled=false')
        # 僞裝成Win10 Chrome用戶
        self.chrome_options.add_argument('--user-agent=""Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36""')
        self.client = None
        # self.client = webdriver.Chrome(chrome_options=self.chrome_options)
        self.index_url = 'https://xxxxx/xxxxx/xxxxx'
        self.report_url = 'https://xxxxx/xxxxx/xxxxx'
        self.data = [
            ('用戶名', '密碼'),
            ('用戶名', '密碼'),
            ('用戶名', '密碼'),
            ('用戶名', '密碼'),
            ('用戶名', '密碼'),
        ]

    def login(self, _username, _password):
        try:
            self.client = webdriver.Chrome(chrome_options=self.chrome_options)
            print(self.get_current_time() + ' ' + _username + u'開始進行打卡'.encode('utf-8'))
            self.client.get(self.index_url)
            username = self.client.find_element_by_name("username")
            password = self.client.find_element_by_name('password')
            username.send_keys(_username)
            password.send_keys(_password)
            login_button = self.client.find_element_by_xpath('//*[@id="form1"]/div[4]/button')
            login_button.click()
        except NoSuchElementException:
            print(self.get_current_time() + ' ' + u'登錄異常!'.encode('utf-8'))
        else:
            # time.sleep(2)
            print(self.get_current_time() + ' ' + u'登錄成功!'.encode('utf-8'))

    def post_data(self):
        try:
            self.client.get(self.report_url)
            submit_button = self.client.find_element_by_xpath('//*[@id="p1_ctl00_btnSubmit"]/span/span')
            submit_button.click()
            ensure_button = self.client.find_element_by_xpath('//*[@id="fineui_26"]/span/span')
            ensure_button.click()
            # print (client.page_source.encode('utf-8'))
        except NoSuchElementException:
            print(self.get_current_time() + ' ' + u'提交表單異常! 打卡失敗!'.encode('utf-8'))
        else:
            # time.sleep(2)
            print(self.get_current_time() + ' ' + u'打卡成功!\n'.encode('utf-8'))
        finally:
            time.sleep(5)
            self.client.quit()
            print(u'瀏覽器退出...\n--------------\n'.encode('utf-8'))

    def run(self):
        for msg in self.data:
            self.login(msg[0], msg[1])
            self.post_data()
        print('Python script completed at ' + self.get_current_time() + '\n-----------------------------------------------\n')

    @staticmethod
    def get_current_time():
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())


if __name__ == '__main__':
    obj = DailyReport()
    obj.run()

腳本內容需要根據不同網站做對應的修改。

腳本定時執行

這裏我們利用LinuxLinux的內置命令crontabcrontab,關於crontabcrontab的用法請自行百度oror谷歌。

$ crontab -e

如果是首次使用,應該會讓你選擇編輯器,我選擇的vimvim,然後在最後一行加入一行

0 0 * * * python ~/dailyReport.py >> ~/dailyReport.log

這樣就可以做到每天00:0000:00自動執行腳本了。

Chrome在服務器端運行參考博文:https://blog.csdn.net/fengmm521/article/details/79661771

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章