splinter
# 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的更多相关文章
- Splinter学习——不仅仅是自动化测试哦
前两天,想抢购一个小米MIX,结果,一开始抢就没有了.于是想,作为程序猿,总得有点特殊手段吧,比如说一个小脚本.最近在学习python,百度了一下,发现了Splinter这个强大的东东!用了不到两小时 ...
- 利用web工具splinter模拟登陆做自动签到
首先,我需要的工具和组件有: Chrome浏览器 浏览器驱动ChromeDriver Python 3.5 Web应用测试工具Splinter 代码部分: from splinter import B ...
- splinter(python操作浏览器魔魁啊)
from splinter import Browser def main(): browser = Browser() browser.visit('http://google.com') brow ...
- Splinter学习--初探3,两种方式登录QQ邮箱
目前,qq邮箱的登录方式有: 1.利用账号.密码登录 2.快捷登录,前提是你本地已有qq账号登录中 和前面一样,还是先到qq邮箱登录首页,审查页面元素,找到我们进行登录操作所相关的链接.按钮或是输入框 ...
- Splinter学习--初探1,模拟百度搜索
Splinter是以Selenium, PhantomJS 和 zope.testbrowser为基础构建的web自动化测试工具,基本原理同selenium 支持的浏览器包括:Chrome, Fire ...
- python学习之——splinter使用
开始学习使用splinter工具了,目前是摸索中,先熟悉splinter工具的使用方法~~ 实现功能: 打开firefox浏览器->www.baidu.com->输入关键词 python, ...
- python学习之——splinter介绍
Splinter是什么: 是一个用 Python 编写的 Web 应用程序进行验收测试的工具. Splinter执行的时候会自动打开你指定的浏览器,访问指定的URL,然后你所开发的模拟的任何行为,都会 ...
- python splinter
from splinter.browser import Browser with Browser() as b: for url,name in web: b.visit(url) b.fill(' ...
- Python自动化测试工具Splinter简介和使用实例
Splinter 快速介绍 官方网站:http://splinter.cobrateam.info/ 官方介绍: Splinter is an open source tool for testing ...
- 搭建splinter+python环境时遇到的错误
因为不想用urllib2了,没有用过splinter,今天就想试试,毕竟后者支持的功能更人性化/自动化. 1,安装splinter 安装过程很简单,安装了pip的话,执行: $ [sudo] pip ...
随机推荐
- Visual stuio2015 升级 Update 3+安装.Net Core 安装包之后,无法创建Mvc项目
原因: 怀疑是更新后缺少Web Frameworks and Tools 工具, 安装update3的时候提示异常 解决方法: 1.去微软 下载 Web Frameworks and Tools安装后 ...
- JAVA-ORM框架整理➣Mybatis操作MySQL
概述 在Java中,对数据库操作的框架很多,上节概述Hibernate的简单使用,这里简单整理Mybatis的使用.Mybatis也是简单的数据库操作框架,通过IOC方式,获取操作类对象,进行数据的操 ...
- Spring MVC基础知识整理➣数据校验与格式化
概述 将view中Form的数据提交到后台之后,后台如何验证数据的有效性?在这里Spring MVC提供了相应的Hibernate类包(hibernate-validator-4.3.1.Final. ...
- windows下面使用nssm设置新的服务实现开机自启等
1.下载: http://nssm.cc/download/?page=download 2.解压: 根据自己的系统选择相应的32bit或者64bit,然后将相应的可执行文件拷贝到系统环境中.配置环境 ...
- Python_xml
xml: 可扩展标记语言,用来标记数据,定义数据类型,主要用来传输和存储数据(和json差不多,不同语言或程序之间进行数据交换的协议) ET(xml.etree.ElementTree)中的几个类: ...
- Codeforces 868F Yet Another Minimization Problem 决策单调性 (看题解)
Yet Another Minimization Problem dp方程我们很容易能得出, f[ i ] = min(g[ j ] + w( j + 1, i )). 然后感觉就根本不能优化. 然后 ...
- $on在构造器外部添加事件$once执行一次的事件$off关闭事件
$on 在构造器外部添加事件. $on接收两个参数,第一个参数是调用时的事件名称,第二个参数是一个匿名方法. 如果按钮在作用域外部,可以利用$emit来执行. html <div id=&quo ...
- 51Nod1336 RMQ逆问题 其他
原文链接https://www.cnblogs.com/zhouzhendong/p/51Nod1336.html 题目传送门 - 51Nod1336 题意 题解 我们将输入的一个区间的答案称为 V ...
- Fruit Ninja(随机数rand())
链接:https://www.nowcoder.com/acm/contest/163/A来源:牛客网 题目描述 Fruit Ninja is a juicy action game enjoyed ...
- 在netcore中实现字段和属性注入
简单来说,使用Ioc模式需要两个步骤,第一是把服务注册到容器中,第二是从容器中获取服务,我们一个一个讨论并演化.这里不会考虑使用如Autofac等第三方的容器来代替默认容器,只是提供一些简单实用的小方 ...