Python 標(biāo)準(zhǔn)庫(kù)中有很多實(shí)用的工具類(lèi),但是在具體使用時(shí),標(biāo)準(zhǔn)庫(kù)文檔上對(duì)使用細(xì)節(jié)描述的并不清楚,比如 urllib2 這個(gè) HTTP 客戶(hù)端庫(kù)。這里總結(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 來(lái)設(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 并沒(méi)有暴露 Timeout 的設(shè)置,要設(shè)置 Timeout 值,只能更改 Socket 的全局 Timeout 值。
import urllib2 import socket socket.setdefaulttimeout(10) # 10 秒鐘后超時(shí) urllib2.socket.setdefaulttimeout(10) # 另一種方式
在 Python 2.6 以后,超時(shí)可以通過(guò) urllib2.urlopen() 的 timeout 參數(shù)直接設(shè)置。
import urllib2 response = urllib2.urlopen('http://www.google.com', timeout=10)
在 HTTP Request 中加入特定的 Header
要加入 header,需要使用 Request 對(duì)象:
import urllib2 request = urllib2.Request(uri) request.add_header('User-Agent', 'fake-client') response = urllib2.urlopen(request)
對(duì)有些 header 要特別留意,服務(wù)器會(huì)針對(duì)這些 header 做檢查
User-Agent : 有些服務(wù)器或 Proxy 會(huì)通過(guò)該值來(lái)判斷是否是瀏覽器發(fā)出的請(qǐng)求
Content-Type : 在使用 REST 接口時(shí),服務(wù)器會(huì)檢查該值,用來(lái)確定 HTTP Body 中的內(nèi)容該怎樣解析。常見(jiàn)的取值有:
- 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ì)針對(duì) HTTP 3XX 返回碼自動(dòng)進(jìn)行 redirect 動(dòng)作,無(wú)需人工配置。要檢測(cè)是否發(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 庫(kù)之外,還可以自定義 HTTPRedirectHandler 類(lèi)。
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 對(duì) 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 庫(kù)。雖然如此,我們還是能通過(guò)下面的方式,使 urllib2 能夠發(fā)出 PUT 或 DELETE 的請(qǐng)求:
import urllib2 request = urllib2.Request(uri, data=data) request.get_method = lambda: 'PUT' # or 'DELETE' response = urllib2.urlopen(request)
得到 HTTP 的返回碼
對(duì)于 200 OK 來(lái)說(shuō),只要使用 urlopen 返回的 response 對(duì)象的 getcode() 方法就可以得到 HTTP 的返回碼。但對(duì)其它返回碼來(lái)說(shuō),urlopen 會(huì)拋出異常。這時(shí)候,就要檢查異常對(duì)象的 code 屬性了:
import urllib2 try: response = urllib2.urlopen('http://restrict.web.com') except urllib2.HTTPError, e: print e.code Debug Log
使用 urllib2 時(shí),可以通過(guò)下面的方法把 debug Log 打開(kāi),這樣收發(fā)包的內(nèi)容就會(huì)在屏幕上打印出來(lái),方便調(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的博客頁(yè)面,發(fā)現(xiàn)可以使用python來(lái)抓取.記得前段時(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來(lái)抓取站點(diǎn)然后使用PyRSS2Gen來(lái)生成RSS并保存為xml格式文件.
順便共享下我生成的RSS地址
http://104.224.129.109/myrss/oschina.xml
大家如果不想折騰的話(huà)直接使用feedly訂閱就行了.
腳本我會(huì)每10分鐘執(zhí)行一次的.
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
