国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

解決Requests中文亂碼

2019-11-11 06:31:57
字體:
來源:轉載
供稿:網友

都在推薦用Requests庫,而不是Urllib,但是讀取網頁的時候中文會出現亂碼。

分析: r = requests.get(“http://www.baidu.com“) **r.text返回的是Unicode型的數據。 使用r.content返回的是bytes型的數據。 也就是說,如果你想取文本,可以通過r.text。 如果想取圖片,文件,則可以通過r.content。**

獲取一個網頁的內容

方法1:使用r.content,得到的是bytes型,再轉為str

url='http://music.baidu.com'r = requests.get(url)html=r.contenthtml_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")PRint(html_doc)

方法2:使用r.text Requests 會自動解碼來自服務器的內容。大多數 unicode 字符集都能被無縫地解碼。請求發出后,Requests 會基于 HTTP 頭部對響應的編碼作出有根據的推測。當你訪問 r.text 之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,并且能夠使用 r.encoding 屬性來改變它. 但是Requests庫的自身編碼為: r.encoding = ‘ISO-8859-1’ 可以 r.encoding 修改編碼

url='http://music.baidu.com'r=requests.get(url)r.encoding='utf-8'print(r.text)

獲取一個網頁的內容后存儲到本地

方法1:r.content為bytes型,則open時需要open(filename,”wb”)

r=requests.get("music.baidu.com")html=r.contentwith open('test5.html','wb') as f: f.write(html)

方法2:r.content為bytes型,轉為str后存儲

r = requests.get("http://www.baidu.com")html=r.contenthtml_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")# print(html_doc)with open('test5.html','w',encoding="utf-8") as f: f.write(html_doc)

方法3:r.text為str,可以直接存儲

r=requests.get("http://www.baidu.com")r.encoding='utf-8'html=r.textwith open('test6.html','w',encoding="utf-8") as f: f.write(html)

Requests+lxml

# -*-coding:utf8-*-import requestsfrom lxml import etreeurl="http://music.baidu.com"r=requests.get(url)r.encoding="utf-8"html=r.text# print(html)selector = etree.HTML(html)title=selector.xpath('//title/text()')print (title[0])

結果為:百度音樂-聽到極致

終極解決方法

以上的方法雖然不會出現亂碼,但是保存下來的網頁,圖片不顯示,只顯示文本。而且打開速度慢,找到了一篇博客,提出了一個終極方法,非常棒。

來自博客 http://blog.chinaunix.net/uid-13869856-id-5747417.html的解決方案:

# -*-coding:utf8-*-import requestsreq = requests.get("http://news.sina.com.cn/")if req.encoding == 'ISO-8859-1': encodings = requests.utils.get_encodings_from_content(req.text) if encodings: encoding = encodings[0] else: encoding = req.apparent_encoding # encode_content = req.content.decode(encoding, 'replace').encode('utf-8', 'replace') global encode_content encode_content = req.content.decode(encoding, 'replace') #如果設置為replace,則會用?取代非法字符;print(encode_content)with open('test.html','w',encoding='utf-8') as f: f.write(encode_content)
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 延安市| 中方县| 弥勒县| 渭源县| 无棣县| 峨边| 博白县| 防城港市| 临漳县| 贵定县| 高邑县| 郓城县| 天峨县| 延寿县| 海阳市| 志丹县| 翁源县| 息烽县| 沈丘县| 黑龙江省| 巍山| 南岸区| 台北县| 平泉县| 乐陵市| 逊克县| 永寿县| 莒南县| 察雅县| 巴楚县| 大同县| 徐州市| 余江县| 平湖市| 泗阳县| 孝义市| 长沙市| 普定县| 彭州市| 维西| 武定县|