都在推薦用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)結果為:百度音樂-聽到極致
以上的方法雖然不會出現亂碼,但是保存下來的網頁,圖片不顯示,只顯示文本。而且打開速度慢,找到了一篇博客,提出了一個終極方法,非常棒。
來自博客 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)新聞熱點
疑難解答