都在推薦用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.content
html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
print(html_doc)
- 1
- 2
- 3
- 4
- 5
方法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
- 2
- 3
- 4
獲取一個網頁的內容後存儲到本地
方法1:r.content爲bytes型,則open時需要open(filename,”wb”)
r=requests.get("music.baidu.com")
html=r.content
with open('test5.html','wb') as f:
f.write(html)
- 1
- 2
- 3
- 4
方法2:r.content爲bytes型,轉爲str後存儲
r = requests.get("http://www.baidu.com")
html=r.content
html_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)
- 1
- 2
- 3
- 4
- 5
- 6
方法3:r.text爲str,可以直接存儲
r=requests.get("http://www.baidu.com")
r.encoding='utf-8'
html=r.text
with open('test6.html','w',encoding="utf-8") as f:
f.write(html)
- 1
- 2
- 3
- 4
- 5
Requests+lxml
# -*-coding:utf8-*-
import requests
from lxml import etree
url="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])
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
結果爲:百度音樂-聽到極致
終極解決方法
以上的方法雖然不會出現亂碼,但是保存下來的網頁,圖片不顯示,只顯示文本。而且打開速度慢,找到了一篇博客,提出了一個終極方法,非常棒。
來自博客
http://blog.chinaunix.net/uid-13869856-id-5747417.html的解決方案:
# -*-coding:utf8-*-
import requests
req = 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)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22