您的位置:首页技术文章
文章详情页

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

【字号: 日期:2022-07-26 18:11:34浏览:9作者:猪猪

解决方法:

先encode再quote。

原理:

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

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

例子:

# -*- coding: UTF-8 -*-# python2.7from urllib import quoteimport 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 objlist_a = parse_js(data_a) # 把 json字典({KEY:’value’}) 转换为python的字典({’key’:’value’})

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

标签: Python 编程