深入解析Python中的urllib2模塊
Python 標(biāo)準(zhǔn)庫中有很多實(shí)用的工具類,但是在具體使用時(shí),標(biāo)準(zhǔn)庫文檔上對使用細(xì)節(jié)描述的并不清楚,比如 urllib2 這個(gè) HTTP 客戶端庫。這里總結(jié)了一些 urllib2 的使用細(xì)節(jié)。
- Proxy 的設(shè)置
- Timeout 設(shè)置
- 在 HTTP Request 中加入特定的 Header
- Redirect
- Cookie
- 使用 HTTP 的 PUT 和 DELETE 方法
- 得到 HTTP 的返回碼
- Debug Log
Proxy 的設(shè)置
urllib2 默認(rèn)會(huì)使用環(huán)境變量 http_proxy 來設(shè)置 HTTP Proxy。如果想在程序中明確控制 Proxy 而不受環(huán)境變量的影響,可以使用下面的方式
import urllib2 enable_proxy = True proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'}) null_proxy_handler = urllib2.ProxyHandler({}) if enable_proxy: opener = urllib2.build_opener(proxy_handler) else: opener = urllib2.build_opener(null_proxy_handler) urllib2.install_opener(opener)
這里要注意的一個(gè)細(xì)節(jié),使用 urllib2.install_opener() 會(huì)設(shè)置 urllib2 的全局 opener 。這樣后面的使用會(huì)很方便,但不能做更細(xì)粒度的控制,比如想在程序中使用兩個(gè)不同的 Proxy 設(shè)置等。比較好的做法是不使用 install_opener 去更改全局的設(shè)置,而只是直接調(diào)用 opener 的 open 方法代替全局的 urlopen 方法。
Timeout 設(shè)置
在老版 Python 中,urllib2 的 API 并沒有暴露 Timeout 的設(shè)置,要設(shè)置 Timeout 值,只能更改 Socket 的全局 Timeout 值。
import urllib2 import socket socket.setdefaulttimeout(10) # 10 秒鐘后超時(shí) urllib2.socket.setdefaulttimeout(10) # 另一種方式
在 Python 2.6 以后,超時(shí)可以通過 urllib2.urlopen() 的 timeout 參數(shù)直接設(shè)置。
import urllib2 response = urllib2.urlopen('http://www.google.com', timeout=10)
在 HTTP Request 中加入特定的 Header
要加入 header,需要使用 Request 對象:
import urllib2 request = urllib2.Request(uri) request.add_header('User-Agent', 'fake-client') response = urllib2.urlopen(request)
對有些 header 要特別留意,服務(wù)器會(huì)針對這些 header 做檢查
User-Agent : 有些服務(wù)器或 Proxy 會(huì)通過該值來判斷是否是瀏覽器發(fā)出的請求
Content-Type : 在使用 REST 接口時(shí),服務(wù)器會(huì)檢查該值,用來確定 HTTP Body 中的內(nèi)容該怎樣解析。常見的取值有:
- application/xml : 在 XML RPC,如 RESTful/SOAP 調(diào)用時(shí)使用
- application/json : 在 JSON RPC 調(diào)用時(shí)使用
- application/x-www-form-urlencoded : 瀏覽器提交 Web 表單時(shí)使用
在使用服務(wù)器提供的 RESTful 或 SOAP 服務(wù)時(shí), Content-Type 設(shè)置錯(cuò)誤會(huì)導(dǎo)致服務(wù)器拒絕服務(wù)
Redirect
urllib2 默認(rèn)情況下會(huì)針對 HTTP 3XX 返回碼自動(dòng)進(jìn)行 redirect 動(dòng)作,無需人工配置。要檢測是否發(fā)生了 redirect 動(dòng)作,只要檢查一下 Response 的 URL 和 Request 的 URL 是否一致就可以了。
import urllib2 response = urllib2.urlopen('http://www.google.cn') redirected = response.geturl() == 'http://www.google.cn'
如果不想自動(dòng) redirect,除了使用更低層次的 httplib 庫之外,還可以自定義 HTTPRedirectHandler 類。
import urllib2 class RedirectHandler(urllib2.HTTPRedirectHandler): def http_error_301(self, req, fp, code, msg, headers): pass def http_error_302(self, req, fp, code, msg, headers): pass opener = urllib2.build_opener(RedirectHandler) opener.open('http://www.google.cn')
Cookie
urllib2 對 Cookie 的處理也是自動(dòng)的。如果需要得到某個(gè) Cookie 項(xiàng)的值,可以這么做:
import urllib2 import cookielib cookie = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie)) response = opener.open('http://www.google.com') for item in cookie: if item.name == 'some_cookie_item_name': print item.value
使用 HTTP 的 PUT 和 DELETE 方法
urllib2 只支持 HTTP 的 GET 和 POST 方法,如果要使用 HTTP PUT 和 DELETE ,只能使用比較低層的 httplib 庫。雖然如此,我們還是能通過下面的方式,使 urllib2 能夠發(fā)出 PUT 或 DELETE 的請求:
import urllib2 request = urllib2.Request(uri, data=data) request.get_method = lambda: 'PUT' # or 'DELETE' response = urllib2.urlopen(request)
得到 HTTP 的返回碼
對于 200 OK 來說,只要使用 urlopen 返回的 response 對象的 getcode() 方法就可以得到 HTTP 的返回碼。但對其它返回碼來說,urlopen 會(huì)拋出異常。這時(shí)候,就要檢查異常對象的 code 屬性了:
import urllib2 try: response = urllib2.urlopen('http://restrict.web.com') except urllib2.HTTPError, e: print e.code Debug Log
使用 urllib2 時(shí),可以通過下面的方法把 debug Log 打開,這樣收發(fā)包的內(nèi)容就會(huì)在屏幕上打印出來,方便調(diào)試,有時(shí)可以省去抓包的工作
import urllib2 httpHandler = urllib2.HTTPHandler(debuglevel=1) httpsHandler = urllib2.HTTPSHandler(debuglevel=1) opener = urllib2.build_opener(httpHandler, httpsHandler) urllib2.install_opener(opener) response = urllib2.urlopen('http://www.google.com')
PS: 借助urllib2抓取網(wǎng)站生成RSS
看了看OsChina的博客頁面,發(fā)現(xiàn)可以使用python來抓取.記得前段時(shí)間看到有人使用python的RSS模塊PyRSS2Gen生成了RSS.于是忍不住手癢自己試著實(shí)現(xiàn)了下,幸好還是成功了,下面代碼共享給大家.
首先需要安裝PyRSS2Gen模塊和BeautifulSoup模塊,pip安裝下就好了,我就不再贅述了.
下面貼出代碼
# -*- coding: utf-8 -*- from bs4 import BeautifulSoup import urllib2 import datetime import time import PyRSS2Gen from email.Utils import formatdate import re import sys import os reload(sys) sys.setdefaultencoding('utf-8') class RssSpider(): def __init__(self): self.myrss = PyRSS2Gen.RSS2(title='OSChina', link='http://my.oschina.net', description=str(datetime.date.today()), pubDate=datetime.datetime.now(), lastBuildDate = datetime.datetime.now(), items=[] ) self.xmlpath=r'/var/www/myrss/oschina.xml' self.baseurl="http://www.oschina.net/blog" #if os.path.isfile(self.xmlpath): #os.remove(self.xmlpath) def useragent(self,url): i_headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) \ AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36", \ "Referer": 'http://baidu.com/'} req = urllib2.Request(url, headers=i_headers) html = urllib2.urlopen(req).read() return html def enterpage(self,url): pattern = re.compile(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}') rsp=self.useragent(url) soup=BeautifulSoup(rsp) timespan=soup.find('div',{'class':'BlogStat'}) timespan=str(timespan).strip().replace('\n','').decode('utf-8') match=re.search(r'\d{4}\S\d{2}\S\d{2}\s\d{2}\S\d{2}',timespan) timestr=str(datetime.date.today()) if match: timestr=match.group() #print timestr ititle=soup.title.string div=soup.find('div',{'class':'BlogContent'}) rss=PyRSS2Gen.RSSItem( title=ititle, link=url, description = str(div), pubDate = timestr ) return rss def getcontent(self): rsp=self.useragent(self.baseurl) soup=BeautifulSoup(rsp) ul=soup.find('div',{'id':'RecentBlogs'}) for li in ul.findAll('li'): div=li.find('div') if div is not None: alink=div.find('a') if alink is not None: link=alink.get('href') print link html=self.enterpage(link) self.myrss.items.append(html) def SaveRssFile(self,filename): finallxml=self.myrss.to_xml(encoding='utf-8') file=open(self.xmlpath,'w') file.writelines(finallxml) file.close() if __name__=='__main__': rssSpider=RssSpider() rssSpider.getcontent() rssSpider.SaveRssFile('oschina.xml')
可以看到,主要是使用BeautifulSoup來抓取站點(diǎn)然后使用PyRSS2Gen來生成RSS并保存為xml格式文件.
順便共享下我生成的RSS地址
http://104.224.129.109/myrss/oschina.xml
大家如果不想折騰的話直接使用feedly訂閱就行了.
腳本我會(huì)每10分鐘執(zhí)行一次的.
- Python urllib模塊urlopen()與urlretrieve()詳解
- Python的Urllib庫的基本使用教程
- python使用urllib2提交http post請求的方法
- 零基礎(chǔ)寫python爬蟲之urllib2使用指南
- python中使用urllib2獲取http請求狀態(tài)碼的代碼例子
- Python使用urllib模塊的urlopen超時(shí)問題解決方法
- python中urllib模塊用法實(shí)例詳解
- 用Python的urllib庫提交WEB表單
- python3使用urllib模塊制作網(wǎng)絡(luò)爬蟲
- python爬蟲之urllib庫常用方法用法總結(jié)大全
相關(guān)文章
Python實(shí)現(xiàn)控制臺(tái)中的進(jìn)度條功能代碼
下面小編就為大家分享一篇Python實(shí)現(xiàn)控制臺(tái)中的進(jìn)度條功能代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12詳細(xì)總結(jié)Python類的多繼承知識(shí)
Python類的多繼承知識(shí)是非常易于新手理解的,如果你是剛剛?cè)腴TPython的話,歡迎參考本篇文章,本文對Python類的多繼承知識(shí)作出了非常詳細(xì)的解釋,還有相關(guān)代碼參考哦。2021-05-05Python實(shí)現(xiàn)讀取mat、tif和hdr格式數(shù)據(jù)
遙感影像數(shù)據(jù)大多以tif格式或者以hdr格式進(jìn)行存儲(chǔ),如果以mat格式進(jìn)行存儲(chǔ),不會(huì)保留坐標(biāo)信息,本文將詳細(xì)介紹如何使用python來讀取這三種格式的數(shù)據(jù),需要的可以參考下2023-12-12四種Python機(jī)器學(xué)習(xí)超參數(shù)搜索方法總結(jié)
在建模時(shí)模型的超參數(shù)對精度有一定的影響,而設(shè)置和調(diào)整超參數(shù)的取值,往往稱為調(diào)參。本文將演示在sklearn中支持的四種基礎(chǔ)超參數(shù)搜索方法,需要的可以參考一下2022-11-11Python Selenium 設(shè)置元素等待的三種方式
這篇文章主要介紹了Python Selenium 設(shè)置元素等待的三種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03Python?中如何使用requests模塊發(fā)布表單數(shù)據(jù)
requests 庫是 Python 的主要方面之一,用于創(chuàng)建對已定義 URL 的 HTTP 請求,本篇文章介紹了 Python requests 模塊,并說明了我們?nèi)绾问褂迷撃K在 Python 中發(fā)布表單數(shù)據(jù),感興趣的朋友跟隨小編一起看看吧2023-06-06