1. 程式人生 > >python簡單爬去油價信息發送到公眾號

python簡單爬去油價信息發送到公眾號

%d 為什麽 ads nco auth odin arc __main__ html

基於這段時間廣州的油價變化的比較大,所以我自己查看油價的網站也增多了,但是作為一個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 = '(&nbsp;&nbsp;&nbsp;&nbsp;)(.*?)(<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的初學者,所以望各位大神多多指教

python簡單爬去油價信息發送到公眾號