Python + selenium实现自动打卡
前言
近几日迫于被辅导员三番五次的提醒每日一报打卡,就想着去写个脚本挂在服务器上定时执行。经过我不懈的努力,最终选择了
,因为简单(
安装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
import time
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox') # 这个配置很重要
client = webdriver.Chrome(chrome_options=chrome_options, executable_path='/home/ubuntu/chromedriver') # 如果没有把chromedriver加入到PATH(如usr/bin)中,就需要指明路径
try:
client.get('https://xxxxx/xxx/login')
name = client.find_element_by_name("username")
password = client.find_element_by_name('password')
name.send_keys('用户名')
password.send_keys('密码')
login_button = client.find_element_by_xpath('//*[@id="form1"]/div[4]/button')
login_button.click()
except:
print(self.getCurrentTime(), u'登录异常!'.encode('utf8'))
else:
print(u'登录成功!'.encode('utf8'))
try:
client.get('https://xxxxxx')
client.get('https://xxxxxx')
submit_button = client.find_element_by_xpath('//*[@id="p1_ctl00_btnSubmit"]/span/span')
submit_button.click()
ensure_button = client.find_element_by_xpath('//*[@id="fineui_26"]/span/span')
ensure_button.click()
except:
print(self.getCurrentTime(), u'提交表单异常! 打卡失败!'.encode('utf8'))
else:
print(u'打卡成功!'.encode('utf8'))
finally:
client.quit()
print(u'浏览器退出...'.encode('utf8'))
# 输出完成时间
print('my python scirpt complete -> ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + '\n')
脚本内容需要根据不同网站做对应的修改。
脚本定时执行
这里我们利用 的内置命令 ,关于 的用法请自行百度 谷歌。
$ crontab -e
如果是首次使用,应该会让你选择编辑器,我选择的 ,然后在最后一行加入一行
0 0 * * * python ~/dailyReport.py >> ~/dailyReport.log
这样就可以做到每天 自动执行脚本了。
注
Chrome在服务器端运行参考博文:https://blog.csdn.net/fengmm521/article/details/79661771