当前位置: 移动技术网 > IT编程>脚本编程>Python > 解决Python发送Http请求时,中文乱码的问题

解决Python发送Http请求时,中文乱码的问题

2020年05月15日  | 移动技术网IT编程  | 我要评论

傲剑洞箫,卡斯罗犬价格,康佳电视自动关机

解决方法:

先encode再quote。

原理:

msg.encode('utf-8')是解决中文乱码问题。

quote():假如url的 name 或者 value 值中有『&』、『%』或者『=』等符号,就会有问题。所以url中的参数字符串也需要把『&=』等符号进行编码,quote()就是对参数字符串中的『&=%』等符号进行编码。

例子:

# -*- coding: utf-8 -*-
# python2.7
from urllib import quote
import requests
 
def httpget(surl):
 header = {}
 try:
  response=requests.get(surl, headers=header)
  stext = response.text
  return stext
 except baseexception:
  print baseexception
   
def demo(msg):
 sencodemsg = quote(msg.encode('utf-8'))
 url = 'http://www.youdao.com/w/eng/' + sencodemsg
 print httpget (url)
 
demo(u'90%的数据') 

补充知识:python 用request payload 翻页获取不同的返回值

我就废话不多说啦,直接看代码吧!

headers={'accept':'*/*',
'accept-encoding': 'gzip, deflate',
'accept-language': 'zh-cn,zh;q=0.9',
'ajax-method': 'getpagejyxtxxfb',
'connection': 'keep-alive',
'content-length': '129',
'content-type': 'text/plain; charset=utf-8',
'cookie': 'asp.net_sessionid=vdl5ooxkjkazwszgvj5woewh',
'host': 'ggzy.yibin.gov.cn',
'origin': 'http://ggzy.yibin.gov.cn',
'referer': 'http://ggzy.yibin.gov.cn/jyweb/zhaobaogonggaolist.aspx?type=%e5%bb%ba%e8%ae%be%e5%b7%a5%e7%a8%8b&subtype=260',
'user-agent': 'mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, like gecko) chrome/67.0.3396.62 safari/537.36',
}      #模仿浏览器 
 payload=[i*15,15,"fbsj desc","xmmc","","xxlb ={0} and xttype={1} and zbfs != 2","[{\"pvalue\":\"260\"},{\"pvalue\":\"1\"}]"] #request payload里面的信息
 
 rsp=requests.post(url1,data=json.dumps(payload),headers = headers) #用request payload里面的信息发送post请求
 data_a=rsp.content 

def parse_js(expr):
 obj = eval(expr, type('dummy', (dict,), dict(__getitem__=lambda s, n: n))())
 return obj

list_a = parse_js(data_a)    # 把 json字典({key:'value'}) 转换为python的字典({'key':'value'})

以上这篇解决python发送http请求时,中文乱码的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网