python2.7.6 requests模块提交中文验证码,,我的环境:windows


我的环境:windows平台命令行编码GBK,python2.7.6。需要用python提交一个中文验证码,目标地址的网页编码为utf-8,目前自己模拟了服务端。http请求使用python的requests模块,但是返回的结果往往不正常,代码如下:

客户端:

# python代码code = '中文验证'# 这里面的code应该是unicode字符串了post_data = {    'name':'jack',    'password':'123456',    'code':code # u'\u4E2D\u6587\u9A8C\u8BC1'}res = requests.post('http://www.test.com',data=post_data)# 使结果集正确显示中文res = res.contentunicode(res,"utf-8")if '验证码有误' in res:    print 'authcode error,retry...'else:    print 'success'
#这是服务端的PHP代码if ($_POST['code'] == '中文验证'){    $result = $db->insert($_POST);} else {    echo '验证码有误';    $_POST['code'] = $_POST['code'].'e';    $result = $db->insert($_POST);}

然后奇怪的事情出现了,数据库code字段里面插入了一些“中文验证” 和 一些“中文验证e”,请问这是什么情况?如果编码有问题,怎么会时而判断正确时而判断错误呢?

补充声明:
没有乱码的问题,插入数据库都是正常的,其实在定义post_data dic的时候,python本身已经把中文unicode了,但是为什么把这串unicode提交到服务器跟“中文验证”比对的时候,有时候出错,有时候正确呢?

以下是几个乱弹琴,仅供参考

我的建议是如果要比较中文字符串的话,一律转换成unicode之后再比较吧

编橙之家文章,

评论关闭