歡迎您光臨本站 註冊首頁

解決Python發送Http請求時,中文亂碼的問題

←手機掃碼閱讀     火星人 @ 2020-05-01 , reply:0


解決方法:

先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請求時,中文亂碼的問題已經有293次圍觀

http://coctec.com/docs/python/shhow-post-232395.html