基于这段时间广州的油价变化的比较大,所以我自己查看油价的网站也增多了,但是作为一个Programmer来说这不是侮辱吗??能用代码实现的为什么要用人力呢???所以就自己做了一个简单的爬去油价信息的python脚本,后来发现执行脚本还是比较麻烦,就定期每天爬去信息发送到对应的公众号上!话不多说,直接上脚本。
(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上定时执行脚本:
(env1) ? python_scripts crontab -l 45 8 * * * /usr/local/bin/python /home/python_scripts/youjia_wechat.py > /dev/null 2>&1
在公众号上就可以知道每天油价的信息了
python的初学者,所以望各位大神多多指教
原文地址:http://blog.51cto.com/legehappy/2130039
时间: 2024-11-12 03:08:30