基於這段時間廣州的油價變化的比較大,因此我本身查看油價的網站也增多了,可是做爲一個Programmer來講這不是侮辱嗎??能用代碼實現的爲何要用人力呢???因此就本身作了一個簡單的爬去油價信息的python腳本,後來發現執行腳本仍是比較麻煩,就按期天天爬去信息發送到對應的公衆號上!話很少說,直接上腳本。html
(env1) ➜ python_scripts cat youjia_wechat.py #!/usr/bin/python #-*- coding:utf-8 -*- #__author__ == 'chenmingle' import requests import json import sys reload(sys) sys.setdefaultencoding('utf-8') import urllib3 import time import urllib import re url = r'http://youjia.chemcp.com/guangdong/guangzhoushi.html' res = urllib.urlopen(url) html = res.read().decode('gb2312') par = '( )(.*?)(<br />)' web = re.search(par,html).group(2) web = web.split(' ',1)[0] cml = web.replace('<font color="red">',':') cml = cml.replace('</font>','') cml = cml.replace(',','\n') cml = cml.replace(':','\n',1) cml = cml.replace(',','\n') print cml class weChat: def __init__(self,Corpid,Secret): url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s' % (Corpid,Secret) res = self.url_req(url) self.token = res["access_token"] def url_req(self,url): requests.packages.urllib3.disable_warnings() req = requests.get(url, verify=False) res = json.loads(req.text) return res def send_message(self,user,content): url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s" % self.token data = { "touser": user, "msgtype": "text", "agentid": 1000002, "text": { "content": content }, "safe":"0" } requests.packages.urllib3.disable_warnings() res = requests.post(url,json=data, verify=False) if json.loads(res.content)['errmsg'] == 'ok': return "send message sucessed" else: return res localtime = time.strftime("%Y-%m-%d %H:%M:%S") a = "廣州油價信息:" if __name__ == '__main__': user = '@all' title = a msg = cml content = a + '\n' + cml get_token = weChat('wxf******','**********pFou7***8') print get_token.send_message(user, content)
最後加上crontab上定時執行腳本:python
(env1) ➜ python_scripts crontab -l 45 8 * * * /usr/local/bin/python /home/python_scripts/youjia_wechat.py > /dev/null 2>&1
在公衆號上就能夠知道天天油價的信息了web
python的初學者,因此望各位大神多多指教json