前幾天趕時間,臨時寫完直接丟客戶了。使用還是可以的 ,但是真正商用我覺得還有一定差距,我使用簡單的文件讀寫來記錄各種數據。
使用該源碼需要注意以下幾點:(私信小編007即可獲取大量Python學習資料,視頻教程以及各類PDF!)
- 微信公眾 令牌 (Token)
- 微信公眾 消息加解密密鑰(EncodingAESKey)
- 微信公眾 APPID
一個你自己的CMS 系統可以使用大淘客 ,需要用到其中的一個Appkey然後把你的服務器地址設置到公眾號上面。
依賴庫
- web框架
- BeautifulSoup 爬蟲
- WXBizMsgCrypt 微信信息加解密
Python 代碼:
# encoding: utf-8
import web
import urllib2
import hashlib
import json
from bs4 import BeautifulSoup
from WXBizMsgCrypt import WXBizMsgCrypt
import xml.dom.minidom
import sys
import time
import os
reload(sys)
sys.setdefaultencoding('utf-8')
H = {
"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6"
}
# 路由信息
urls = (
'/', 'index',
'/findProduct.action', 'findProduct',
'/checkSignature', 'checkSignature',
'/coupon', 'coupon'
)
encodingAESKey = '自己寫'
token = "自己寫"
appid = "自己寫"
daTaoKeAppKey = "自己寫"
# 格式化模板信息
def fromatXml(FromUserName, ToUserName, CreateTime, Content):
return "" " + str(
CreateTime) + "0
# 查找商品
def queryProduct(text):
url = "http://youhui.javalt.cn/index.php?r=l&kw=" + text
req = urllib2.Request(url, headers=H)
text = urllib2.urlopen(req).read()
soup = BeautifulSoup(text)
list = soup.findAll("li", {"class": "theme-hover-border-color-1 g_over"})
count = 0
dict = {}
for item in list:
info = {}
info["name"] = item.div.a.text
info["image"] = item.img.get("src")
info["url"] = item.a.get("href")
data = {}
data["pid"] = item.a.get("data-gid")
data["info"] = info
dict[count] = data
count = count + 1
return json.dumps(dict)
def getProduct(id):
url = "http://api.dataoke.com/index.php?r=port/index&id=" + id + "&appkey="+daTaoKeAppKey+"&v=2"
req = urllib2.Request(url, headers=H)
text = urllib2.urlopen(req).read()
return text
class index:
def GET(self):
return "What are you going to do?"
class findProduct:
def GET(self):
return queryProduct(web.input().query)
# 微信接口
class checkSignature:
def __init__(self):
self.app_root = os.path.dirname(__file__)
self.templates_root = os.path.join(self.app_root, 'templates')
self.render = web.template.render(self.templates_root)
def GET(self):
data = web.input()
signature = data.signature
timestamp = data.timestamp
nonce = data.nonce
echostr = data.echostr
list = [token, timestamp, nonce]
list.sort()
sha1 = hashlib.sha1()
map(sha1.update, list)
hashcode = sha1.hexdigest()
if hashcode == signature:
return echostr
def POST(self):
str_xml = web.data()
decrypt = WXBizMsgCrypt(token, encodingAESKey, appid)
ret, decryp_xml = decrypt.DecryptMsg(str_xml, web.input().msg_signature, web.input().timestamp,
web.input().nonce)
dom = xml.dom.minidom.parseString(decryp_xml)
root = dom.documentElement
msgType = root.getElementsByTagName('MsgType')[0].firstChild.data
fromUser = root.getElementsByTagName('FromUserName')[0].firstChild.data
toUser = root.getElementsByTagName('ToUserName')[0].firstChild.data
# 判斷是否文本信息
if msgType == 'text':
content = root.getElementsByTagName('Content')[0].firstChild.data
pid = None
try:
path = './cache/' + fromUser + '.data'
indexpath = './cache/' + fromUser + '.index'
# 判斷商品信息是否存在
if os.path.exists(path) and content == '換':
# 讀取商品信息Json
file_object = open(path, 'r')
datajson = json.loads(file_object.read())
file_object.close()
# 讀取索引信息
file_object = open(indexpath, 'r')
index = file_object.read()
file_object.close()
# 保存索引信息
file_object = open(indexpath, 'w')
file_object.write(str(int(index) + 1))
file_object.close()
pid = datajson[index]["pid"]
else:
datajson = queryProduct(content)
# 創建文件
file_object = open(path, 'w')
# 保存商品信息Json
file_object.write(datajson)
file_object.close()
# 創建文件
file_object = open(indexpath, 'w')
# 保存索引信息
file_object.write('1')
file_object.close()
pid = json.loads(datajson)['0']["pid"]
hjson = json.loads(getProduct(pid))
print hjson["result"]["Title"]
return self.render.reply_pictext1(fromUser,
toUser,
int(time.time()),
hjson["result"]["Title"],
'在售價: ' + str(hjson["result"]["Org_Price"]) + ' 券後價: ' + str(hjson["result"]["Price"]),
hjson["result"]["Pic"],
"http://student.javalt.cn/coupon?pid=" + hjson["result"]["ID"])
except Exception as e:
return fromatXml(fromUser, toUser, int(time.time()), "沒有查到該商品信息 更多信息可以進入 http://youhui.javalt.cn 查找")
else:
return fromatXml(fromUser, toUser, int(time.time()), "請輸入正確的關鍵字 更多信息可以進入 http://youhui.javalt.cn 查找")
# 跳轉到領取優惠卷頁
class coupon(object):
def GET(self):
return ""
if __name__ == "__main__":
app = web.application(urls, globals())
app.run()
閱讀更多 徒手憶歲月 的文章