都在推薦用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)
方法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.content with open('test5.html','wb') as f: f.write(html)
方法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)
方法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)
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])
結果為:百度音樂-聽到極致
終極解決方法
以上的方法雖然不會出現亂碼,但是保存下來的網頁,圖片不顯示,只顯示文本。而且打開速度慢,找到了一篇博客,提出了一個終極方法,非常棒。
# -*-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)
(function(){ function setArticleH(btnReadmore,posi){ var winH = $(window).height(); var articleBox = $("div.article_content"); var artH = articleBox.height(); if(artH > winH*posi){ articleBox.css({ 'height':winH*posi+'px', 'overflow':'hidden' }) btnReadmore.click(function(){ articleBox.removeAttr("style"); $(this).parent().remove(); }) }else{ btnReadmore.parent().remove(); } } var btnReadmore = $("#btn-readmore"); if(btnReadmore.length>0){ if(currentUserName){ setArticleH(btnReadmore,3); }else{ setArticleH(btnReadmore,1.2); } } })() //