Python + selenium + crontab实现每日定时自动打卡

前言

近几日迫于被辅导员三番五次的提醒每日一报打卡,就想着去写个脚本挂在服务器上定时执行。经过我不懈的努力,最终选择了 s e l e n i u m selenium selenium,因为简单(:

步骤

安装pip

$ sudo apt update
$ sudo apt-get install python-pip

安装selenium库

$ sudo pip install selenium

如果报错

locale.Error: unsupported locale setting

那么就执行

$ sudo apt install language-pack-zh-hans

即可。

安装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 . 

unzip并不是内置命令,所有要提前安装

$ sudo apt install unzip
  • 放到相应目录并授予可执行权限
$ 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

注意要和前面的chromedriver版本一致!

  • 测试调试
$ google-chrome --headless --remote-debugging-port=9222 https://chromium.org --disable-gpu --no-sandbox

编写脚本

  • 创建脚本并授予权限
$ 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()

脚本内容需要根据不同网站做对应的修改。

脚本定时执行

这里我们利用 L i n u x Linux Linux的内置命令 c r o n t a b crontab crontab,关于 c r o n t a b crontab crontab的用法请自行百度 o r or or谷歌。

$ crontab -e

如果是首次使用,应该会让你选择编辑器,我选择的 v i m vim vim,然后在最后一行加入一行

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

这样就可以做到每天 00 : 00 00:00 00:00自动执行脚本了。

Chrome在服务器端运行参考博文:https://blog.csdn.net/fengmm521/article/details/79661771

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值