# coding:utf-8

 import tornado.web
import tornado.options
import tornado.httpserver
import tornado.ioloop
import hashlib
import xmltodict
import time
import tornado.gen
import json
import os from tornado.web import RequestHandler
from tornado.options import options, define
from tornado.httpclient import AsyncHTTPClient, HTTPRequest WECHAT_TOKEN = "itcast"
WECHAT_APP_ID = "wx36766f74dbfeef15"
WECHAT_APP_SECRET = "aaf6dbca95a012895eb570f0ba549ee5" define("port", default=8000, type=int, help="") class AccessToken(object):
"""access_token辅助类"""
_access_token = None
_create_time = 0
_expires_in = 0 @classmethod
@tornado.gen.coroutine
def update_access_token(cls):
client = AsyncHTTPClient()
url = "https://api.weixin.qq.com/cgi-bin/token?" \
"grant_type=client_credential&appid=%s&secret=%s" % (WECHAT_APP_ID, WECHAT_APP_SECRET)
resp = yield client.fetch(url)
dict_data = json.loads(resp.body)
if "errcode" in dict_data:
raise Exception("wechat server error")
else:
cls._access_token = dict_data["access_token"]
cls._expires_in = dict_data["expires_in"]
cls._create_time = time.time() @classmethod
@tornado.gen.coroutine
def get_access_token(cls):
if time.time() - cls._create_time > (cls._expires_in - 200):
# 向微信服务器请求access_token
yield cls.update_access_token()
raise tornado.gen.Return(cls._access_token)
else:
raise tornado.gen.Return(cls._access_token) class WechatHandler(RequestHandler):
"""对接微信服务器"""
def prepare(self):
signature = self.get_argument("signature")
timestamp = self.get_argument("timestamp")
nonce = self.get_argument("nonce")
tmp = [WECHAT_TOKEN, timestamp, nonce]
tmp.sort()
tmp = "".join(tmp)
real_signature = hashlib.sha1(tmp).hexdigest()
if signature != real_signature:
self.send_error(403) def get(self):
echostr = self.get_argument("echostr")
self.write(echostr) def post(self):
xml_data = self.request.body
dict_data = xmltodict.parse(xml_data)
msg_type = dict_data["xml"]["MsgType"]
if msg_type == "text":
content = dict_data["xml"]["Content"]
"""
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好]]></Content>
</xml>
"""
resp_data = {
"xml":{
"ToUserName": dict_data["xml"]["FromUserName"],
"FromUserName": dict_data["xml"]["ToUserName"],
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": content,
}
}
self.write(xmltodict.unparse(resp_data))
elif msg_type == "event":
if dict_data["xml"]["Event"] == "subscribe":
"""用户关注的事件"""
resp_data = {
"xml": {
"ToUserName": dict_data["xml"]["FromUserName"],
"FromUserName": dict_data["xml"]["ToUserName"],
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": u"您来啦,笑而不语",
}
}
if "EventKey" in dict_data["xml"]:
event_key = dict_data["xml"]["EventKey"]
scene_id = event_key[8:]
resp_data["xml"]["Content"] = u"您来啦,笑而不语%s次" % scene_id
self.write(xmltodict.unparse(resp_data))
elif dict_data["xml"]["Event"] == "SCAN":
scene_id = dict_data["xml"]["EventKey"]
resp_data = {
"xml": {
"ToUserName": dict_data["xml"]["FromUserName"],
"FromUserName": dict_data["xml"]["ToUserName"],
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": u"您扫描的是%s" % scene_id,
}
}
self.write(xmltodict.unparse(resp_data)) else:
resp_data = {
"xml": {
"ToUserName": dict_data["xml"]["FromUserName"],
"FromUserName": dict_data["xml"]["ToUserName"],
"CreateTime": int(time.time()),
"MsgType": "text",
"Content": "I love itcast",
}
}
self.write(xmltodict.unparse(resp_data)) class QrcodeHandler(RequestHandler):
"""请求微信服务器生成带参数二维码返回给客户"""
@tornado.gen.coroutine
def get(self):
scene_id = self.get_argument("sid")
try:
access_token = yield AccessToken.get_access_token()
except Exception as e:
self.write("errmsg: %s" % e)
else:
client = AsyncHTTPClient()
url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s" % access_token
req_data = {"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": scene_id}}}
req = HTTPRequest(
url=url,
method="POST",
body=json.dumps(req_data)
)
resp = yield client.fetch(req)
dict_data = json.loads(resp.body)
if "errcode" in dict_data:
self.write("errmsg: get qrcode failed")
else:
ticket = dict_data["ticket"]
qrcode_url = dict_data["url"]
self.write('<img src="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s"><br/>' % ticket)
self.write('<p>%s</p>' % qrcode_url) class ProfileHandler(RequestHandler):
@tornado.gen.coroutine
def get(self):
code = self.get_argument("code")
client = AsyncHTTPClient()
url = "https://api.weixin.qq.com/sns/oauth2/access_token?" \
"appid=%s&secret=%s&code=%s&grant_type=authorization_code" % (WECHAT_APP_ID, WECHAT_APP_SECRET, code)
resp = yield client.fetch(url)
dict_data = json.loads(resp.body)
if "errcode" in dict_data:
self.write("error occur")
else:
access_toke = dict_data["access_token"]
open_id = dict_data["openid"]
url = "https://api.weixin.qq.com/sns/userinfo?" \
"access_token=%s&openid=%s&lang=zh_CN" % (access_toke, open_id)
resp = yield client.fetch(url)
user_data = json.loads(resp.body)
if "errcode" in user_data:
self.write("error occur again")
else:
self.render("index.html", user=user_data) """
用户最终访问的URL
https://open.weixin.qq.com/connect/oauth2/authorize?
appid=wx36766f74dbfeef15&redirect_uri=http%3A//www.idehai.com/wechat8000/profile&response_type=code&scope=snsapi_userinfo
&state=1#wechat_redirect
""" class MenuHandler(RequestHandler):
@tornado.gen.coroutine
def get(self):
try:
access_token = yield AccessToken.get_access_token()
except Exception as e:
self.write("errmsg: %s" % e)
else:
client = AsyncHTTPClient()
url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s" % access_token
menu = {
"button": [
{
"type": "view",
"name": "我的主页",
"url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx36766f74dbfeef15&redirect_uri=http%3A//www.idehai.com/wechat8000/profile&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect"
}
]
}
req = HTTPRequest(
url=url,
method="POST",
body=json.dumps(menu, ensure_ascii=False)
)
resp = yield client.fetch(req)
dict_data = json.loads(resp.body)
if dict_data["errcode"] == 0:
self.write("OK")
else:
self.write("failed") def main():
tornado.options.parse_command_line()
app = tornado.web.Application(
[
(r"/wechat8000", WechatHandler),
(r"/qrcode", QrcodeHandler),
(r"/wechat8000/profile", ProfileHandler),
(r"/menu", MenuHandler),
],
template_path=os.path.join(os.path.dirname(__file__), "template")
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start() if __name__ == "__main__":
main()

 import requests
from time import sleep def check():
url = "https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2018-02-08&leftTicketDTO.from_station=CQW&leftTicketDTO.to_station=CSQ&purpose_codes=ADULT"
#url = "https://kyfw.12306.cn/otn/leftTicket/queryZ?leftTicketDTO.train_date=2018-02-08&leftTicketDTO.from_station=CDW&leftTicketDTO.to_station=CSQ&purpose_codes=ADULT"
res = requests.get(url)
res.encoding = 'utf-8'
dic = res.json()
# print(len(dic['data']['result']))
return dic['data']['result']
# tem_list[23]软卧
# tem_list[24]动卧
# tem_list[25]硬卧
# tem_list[23]软卧
# tem_list[23]软卧 #176 1 k578硬卧
#171 2 k578软卧
ord=0
num = 1
list2 = []
for i in check():
# print(type(i))
tem_list = i.split('|')
# print("tem_list",tem_list[23])
# sleep(1)
# print(type(tem_list),len(tem_list))
# for row in range(22,25):
# print(ord,tem_list[1])
# ord +=1
# print("hhh",tem_list[23])
for row in tem_list:
print(tem_list[num])
print('before%s'%ord)
# print("23",row)
# print('after')
ord +=1
sleep(1)
# print("row",row)
# if row:
# print("row",row)
# list2.append(row)
# else:
# list2.append('null%s'%ord)
# ord +=1 print("ooo",list2) # for n in tem_list:
# print(num,n)
# num += 1
# print(tem_list[1])
# for num in tem_list:
# print(tem_list[num])
# if tem_list[23] !='无' and tem_list[23] != '':
# print(tem_list[3],tem_list[23])
# # print('%s》》》》%s有':(%tem_list[3],%tem_list[23]))
# else:
# print(tem_list[3],tem_list[23])
# print('%s》》》》无'%tem_list[3])

splinter的更多相关文章

  1. Splinter学习——不仅仅是自动化测试哦

    前两天,想抢购一个小米MIX,结果,一开始抢就没有了.于是想,作为程序猿,总得有点特殊手段吧,比如说一个小脚本.最近在学习python,百度了一下,发现了Splinter这个强大的东东!用了不到两小时 ...

  2. 利用web工具splinter模拟登陆做自动签到

    首先,我需要的工具和组件有: Chrome浏览器 浏览器驱动ChromeDriver Python 3.5 Web应用测试工具Splinter 代码部分: from splinter import B ...

  3. splinter(python操作浏览器魔魁啊)

    from splinter import Browser def main(): browser = Browser() browser.visit('http://google.com') brow ...

  4. Splinter学习--初探3,两种方式登录QQ邮箱

    目前,qq邮箱的登录方式有: 1.利用账号.密码登录 2.快捷登录,前提是你本地已有qq账号登录中 和前面一样,还是先到qq邮箱登录首页,审查页面元素,找到我们进行登录操作所相关的链接.按钮或是输入框 ...

  5. Splinter学习--初探1,模拟百度搜索

    Splinter是以Selenium, PhantomJS 和 zope.testbrowser为基础构建的web自动化测试工具,基本原理同selenium 支持的浏览器包括:Chrome, Fire ...

  6. python学习之——splinter使用

    开始学习使用splinter工具了,目前是摸索中,先熟悉splinter工具的使用方法~~ 实现功能: 打开firefox浏览器->www.baidu.com->输入关键词 python, ...

  7. python学习之——splinter介绍

    Splinter是什么: 是一个用 Python 编写的 Web 应用程序进行验收测试的工具. Splinter执行的时候会自动打开你指定的浏览器,访问指定的URL,然后你所开发的模拟的任何行为,都会 ...

  8. python splinter

    from splinter.browser import Browser with Browser() as b: for url,name in web: b.visit(url) b.fill(' ...

  9. Python自动化测试工具Splinter简介和使用实例

    Splinter 快速介绍 官方网站:http://splinter.cobrateam.info/ 官方介绍: Splinter is an open source tool for testing ...

  10. 搭建splinter+python环境时遇到的错误

    因为不想用urllib2了,没有用过splinter,今天就想试试,毕竟后者支持的功能更人性化/自动化. 1,安装splinter 安装过程很简单,安装了pip的话,执行: $ [sudo] pip ...

随机推荐

  1. 一脸懵逼学习MapReduce的原理和编程(Map局部处理,Reduce汇总)和MapReduce几种运行方式

    1:MapReduce的概述: (1):MapReduce是一种分布式计算模型,由Google提出,主要用于搜索领域,解决海量数据的计算问题. (2):MapReduce由两个阶段组成:Map和Red ...

  2. angular 4 开发环境下打包文件过大

    angular 4本地开发环境下,ng server -- port 8080 -o 之后在在浏览器中查看数据请求,其中vendor.bundle.js有8.3mb,而整个传输数据大小为16.3mb ...

  3. bzoj 4621: Tc605 动态规划

    题解: 一道比较简单的题目 想着想着就把题目记错了..想成了可以把某段区间覆盖为其中一个数 其实是比较简单的 每个点的贡献一定是一个区间(就跟zjoi2018那题一样) 然后问题就变成了给你n个区间让 ...

  4. 2016-06-18 exshop第四天

    昨天本来想完成用asset-pipeline替换掉resource插件的工作,但由于进行了对spring security插件的文档解读,同时面试了4个人,每个人耗费了30分钟,并且公司下午4:30组 ...

  5. Django时区的解释

    https://segmentfault.com/q/1010000000405911

  6. MySQL 存储过程中分页

    MySQL数据库中,自定义存储过程查询表中的数据,带有分页功能.具体实例如下代码: 1 DROP PROCEDURE IF EXISTS `sampledb`.`proc_GetPagedDataSe ...

  7. 通过impala更改Kudu表属性

    开发人员可以通过更改表的属性来更改 Impala 与给定 Kudu 表相关的元数据.这些属性包括表名, Kudu 主地址列表,以及表是否由 Impala (内部)或外部管理. Rename an Im ...

  8. 浅谈Rsync+Inotify实时同步

    Rsync是Unix/Linux旗下的一款应用软件,利用它可以是多台服务器数据保持同步一致性,第一次同步时rsync会复制全部内容,但在下次只传输修改过的文件 Rsync在传输数据的过程中可以实行压缩 ...

  9. AtCoder Regular Contest 080 (ARC080) E - Young Maids 线段树 堆

    原文链接http://www.cnblogs.com/zhouzhendong/p/8934377.html 题目传送门 - ARC080 E - Young Maids 题意 给定一个长度为$n$的 ...

  10. P1080 国王游戏 贪心 高精度

    题目描述 恰逢 HH国国庆,国王邀请nn 位大臣来玩一个有奖游戏.首先,他让每个大臣在左.右手上面分别写下一个整数,国王自己也在左.右手上各写一个整数.然后,让这 nn 位大臣排成一排,国王站在队伍的 ...