解決Python發送Http請求時,中文亂碼的問題
解決方法:
先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請求時,中文亂碼的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。