Python发送Http请求时,中文乱码怎么办

发布时间:2020-07-29 11:16:56 作者:小猪
来源:亿速云 阅读:336

这篇文章主要为大家展示了Python发送Http请求时,中文乱码怎么办,内容简而易懂,希望大家可以学习一下,学习完之后肯定会有收获的,下面让小编带大家一起来看看吧。

解决方法:

先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请求时,中文乱码怎么办的内容,如果你们有学习到知识或者技能,可以把它分享出去让更多的人看到。

推荐阅读:
  1. 使用Requests发送Http请求
  2. springboot发送http请求

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python http

上一篇:Django ORM如何查询表中某列字段值

下一篇:如何实现系统高安全性设计

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》