Python網頁抓取urllib,urllib2,httplib[1]


Python網頁抓取urllib,urllib2,httplib[1]       

分類:            Python筆記 78人閱讀 評論(0) 收藏 舉報

前階段使用到ftp,寫了個工具腳本http://blog.csdn.net/wklken/article/details/7059423

最近需要抓網頁,看了下python抓取方式

 

需求:

抓取網頁,解析獲取內容

 

涉及庫:【重點urllib2】

urllib   http://docs.python.org/library/urllib.html

urllib2  http://docs.python.org/library/urllib2.html

httplib   http://docs.python.org/library/httplib.html

 

 

使用urllib:

1.      抓取網頁信息

 

urllib.urlopen(url[, data[, proxies]]) :

url: 表示遠程數據的路徑

data: 以post方式提交到url的數據

proxies:用於設置代理

 

urlopen返回對象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :這些方法的使用方式與文件對象完全一樣

-         info():返回一個httplib.HTTPMessage對象,表示遠程服務器返回的頭信息

-         getcode():返回Http狀態碼。如果是http請求,200請求成功完成;404網址未找到

-         geturl():返回請求的url

 

使用:

[python] view plain copy print ?
  1. #!/usr/bin/python 
  2. # -*- coding:utf-8 -*- 
  3. # urllib_test.py 
  4. # author:wklken 
  5. # 2012-03-17  wklken#yeah.net  
  6.  
  7. import os 
  8. import urllib 
  9. url = "http://www.siteurl.com" 
  10.  
  11. def use_urllib(): 
  12.   import urllib, httplib 
  13.   httplib.HTTPConnection.debuglevel = 1  
  14.   page = urllib.urlopen(url) 
  15.   print"status:", page.getcode() #200請求成功,404 
  16.   print"url:", page.geturl() 
  17.   print"head_info:\n",  page.info() 
  18.   print"Content len:", len(page.read()) 

 

附帶的其他方法:(主要是url編碼解碼)

-         urllib.quote(string[, safe]):對字符串進行編碼。參數safe指定了不需要編碼的字符

-         urllib.unquote(string) :對字符串進行解碼

-          urllib.quote_plus(string [ , safe ] ) :與urllib.quote類似,但這個方法用'+'來替換' ',而quote用'%20'來代替' '

-          urllib.unquote_plus(string ) :對字符串進行解碼

 

-         urllib.urlencode(query[, doseq]):將dict或者包含兩個元素的元組列表轉換成url參數。例如 字典{'name': 'wklken', 'pwd': '123'}將被轉換為"name=wklken&pwd=123"

-         urllib.pathname2url(path):將本地路徑轉換成url路徑

-          urllib.url2pathname(path):將url路徑轉換成本地路徑

 

使用:

[python] view plain copy print ?
  1. def urllib_other_functions(): 
  2.   astr = urllib.quote('this is "K"'
  3.   print astr 
  4.   print urllib.unquote(astr) 
  5.   bstr = urllib.quote_plus('this is "K"'
  6.   print bstr 
  7.   print urllib.unquote(bstr) 
  8.  
  9.   params = {"a":"1", "b":"2"
  10.   print urllib.urlencode(params) 
  11.  
  12.   l2u = urllib.pathname2url(r'd:\a\test.py'
  13.   print l2u  
  14.   print urllib.url2pathname(l2u) 

 

2.  下載遠程數據

 

urlretrieve方法直接將遠程數據下載到本地

urllib.urlretrieve(url[, filename[, reporthook[, data]]]):

 

filename指定保存到本地的路徑(若未指定該,urllib生成一個臨時文件保存數據)

reporthook回調函數,當連接上服務器、以及相應的數據塊傳輸完畢的時候會觸發該回調

data指post到服務器的數據

 

該方法返回一個包含兩個元素的元組(filename, headers),filename表示保存到本地的路徑,header表示服務器的響應頭。

[python] view plain copy print ?
  1. def  callback_f(downloaded_size, block_size, romote_total_size): 
  2.   per = 100.0 * downloaded_size * block_size / romote_total_size 
  3.   if per > 100
  4.     per = 100  
  5.   print"%.2f%%"% per  
  6.  
  7. def use_urllib_retrieve(): 
  8.   import urllib 
  9.   local = os.path.join(os.path.abspath("./"), "a.html"
  10.   print local 
  11.   urllib.urlretrieve(url,local,callback_f) 

下一篇:httplib

轉載請注明出處:http://blog.csdn.net/wklken

 

Python網頁抓取urllib,urllib2,httplib[2]       

分類:            Python筆記 86人閱讀 評論(0) 收藏 舉報

上一篇使用urllib抓取  Python網頁抓取urllib,urllib2,httplib[1]

 

使用httplib抓取:

表示一次與服務器之間的交互,即請求/響應

httplib.HTTPConnection ( host [ , port [ ,strict [ , timeout ]]] )

host表示服務器主機

port為端口號,默認值為80

strict的 默認值為false, 表示在無法解析服務器返回的狀態行時(status line) (比較典型的狀態行如: HTTP/1.0 200 OK ),是否拋BadStatusLine 異常

可選參數timeout 表示超時時間。

 

HTTPConnection提供的方法:

- HTTPConnection.request ( method , url [ ,body [ , headers ]] )

調用request 方法會向服務器發送一次請求

method 表示請求的方法,常用有方法有get 和post ;

url 表示請求的資源的url ;

body 表示提交到服務器的數據,必須是字符串(如果method是”post”,則可以把body 理解為html 表單中的數據);

headers 表示請求的http 頭。

- HTTPConnection.getresponse ()

獲取Http 響應。返回的對象是HTTPResponse 的實例,關於HTTPResponse 在下面會講解。

- HTTPConnection.connect ()

連接到Http 服務器。

- HTTPConnection.close ()

關閉與服務器的連接。

- HTTPConnection.set_debuglevel ( level )

設置高度的級別。參數level 的默認值為0 ,表示不輸出任何調試信息。

 

httplib.HTTPResponse

-HTTPResponse表示服務器對客戶端請求的響應。往往通過調用HTTPConnection.getresponse()來創建,它有如下方法和屬性:

-HTTPResponse.read([amt])

獲取響應的消息體。如果請求的是一個普通的網頁,那么該方法返回的是頁面的html。可選參數amt表示從響應流中讀取指定字節的數據。

-HTTPResponse.getheader(name[, default])

獲取響應頭。Name表示頭域(header field)名,可選參數default在頭域名不存在的情況下作為默認值返回。

-HTTPResponse.getheaders()

以列表的形式返回所有的頭信息。

- HTTPResponse.msg

獲取所有的響應頭信息。

-HTTPResponse.version

獲取服務器所使用的http協議版本。11表示http/1.1;10表示http/1.0。

-HTTPResponse.status

獲取響應的狀態碼。如:200表示請求成功。

-HTTPResponse.reason

返回服務器處理請求的結果說明。一般為”OK”

 

使用例子:

[python] view plain copy print ?
  1. #!/usr/bin/python 
  2. # -*- coding:utf-8 -*- 
  3. # httplib_test.py 
  4. # author:wklken 
  5. # 2012-03-17  wklken#yeah.net  
  6. def use_httplib(): 
  7.   import httplib 
  8.   conn = httplib.HTTPConnection("www.baidu.com"
  9.   i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5"
  10.              "Accept": "text/plain"
  11.   conn.request("GET", "/", headers = i_headers) 
  12.   r1 = conn.getresponse() 
  13.   print"version:", r1.version 
  14.   print"reason:", r1.reason 
  15.   print"status:", r1.status 
  16.   print"msg:", r1.msg 
  17.   print"headers:", r1.getheaders() 
  18.   data = r1.read() 
  19.   print len(data) 
  20.   conn.close() 
  21.  
  22. if __name__ == "__main__"
  23.   use_httplib() 

 

 

        Python網頁抓取urllib,urllib2,httplib[3]       

分類:            Python筆記 80人閱讀 評論(0) 收藏 舉報

 

使用urllib2,太強大了

試了下用代理登陸拉取cookie,跳轉抓圖片......

文檔:http://docs.python.org/library/urllib2.html

 

直接上demo代碼了

包括:直接拉取,使用Reuqest(post/get),使用代理,cookie,跳轉處理

 

[python] view plain copy print ?
  1. #!/usr/bin/python 
  2. # -*- coding:utf-8 -*- 
  3. # urllib2_test.py 
  4. # author: wklken 
  5. # 2012-03-17 wklken@yeah.net 
  6.  
  7.  
  8. import urllib,urllib2,cookielib,socket 
  9.  
  10. url = "http://www.testurl....."#change yourself 
  11. #最簡單方式 
  12. def use_urllib2(): 
  13.   try
  14.     f = urllib2.urlopen(url, timeout=5).read() 
  15.   except urllib2.URLError, e: 
  16.     print e.reason 
  17.   print len(f) 
  18.  
  19. #使用Request 
  20. def get_request(): 
  21.   #可以設置超時 
  22.   socket.setdefaulttimeout(5
  23.   #可以加入參數  [無參數,使用get,以下這種方式,使用post] 
  24.   params = {"wd":"a","b":"2"
  25.   #可以加入請求頭信息,以便識別 
  26.   i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5"
  27.              "Accept": "text/plain"
  28.   #use post,have some params post to server,if not support ,will throw exception 
  29.   #req = urllib2.Request(url, data=urllib.urlencode(params), headers=i_headers) 
  30.   req = urllib2.Request(url, headers=i_headers) 
  31.  
  32.   #創建request后,還可以進行其他添加,若是key重復,后者生效 
  33.   #request.add_header('Accept','application/json') 
  34.   #可以指定提交方式 
  35.   #request.get_method = lambda: 'PUT' 
  36.   try
  37.     page = urllib2.urlopen(req) 
  38.     print len(page.read()) 
  39.     #like get 
  40.     #url_params = urllib.urlencode({"a":"1", "b":"2"}) 
  41.     #final_url = url + "?" + url_params 
  42.     #print final_url 
  43.     #data = urllib2.urlopen(final_url).read() 
  44.     #print "Method:get ", len(data) 
  45.   except urllib2.HTTPError, e: 
  46.     print"Error Code:", e.code 
  47.   except urllib2.URLError, e: 
  48.     print"Error Reason:", e.reason 
  49.  
  50. def use_proxy(): 
  51.   enable_proxy = False 
  52.   proxy_handler = urllib2.ProxyHandler({"http":"http://proxyurlXXXX.com:8080"}) 
  53.   null_proxy_handler = urllib2.ProxyHandler({}) 
  54.   if enable_proxy: 
  55.     opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler) 
  56.   else
  57.     opener = urllib2.build_opener(null_proxy_handler, urllib2.HTTPHandler) 
  58.   #此句設置urllib2的全局opener 
  59.   urllib2.install_opener(opener) 
  60.   content = urllib2.urlopen(url).read() 
  61.   print"proxy len:",len(content) 
  62.  
  63. class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor): 
  64.   def http_error_403(self, req, fp, code, msg, hdrs): 
  65.     return fp 
  66.   def http_error_400(self, req, fp, code, msg, hdrs): 
  67.     return fp 
  68.   def http_error_500(self, req, fp, code, msg, hdrs): 
  69.     return fp 
  70.  
  71. def hand_cookie(): 
  72.   cookie = cookielib.CookieJar() 
  73.   #cookie_handler = urllib2.HTTPCookieProcessor(cookie) 
  74.   #after add error exception handler 
  75.   cookie_handler = NoExceptionCookieProcesser(cookie) 
  76.   opener = urllib2.build_opener(cookie_handler, urllib2.HTTPHandler) 
  77.   url_login = "https://www.yourwebsite/?login" 
  78.   params = {"username":"user","password":"111111"
  79.   opener.open(url_login, urllib.urlencode(params)) 
  80.   for item in cookie: 
  81.     print item.name,item.value 
  82.   #urllib2.install_opener(opener) 
  83.   #content = urllib2.urlopen(url).read() 
  84.   #print len(content) 
  85. #得到重定向 N 次以后最后頁面URL 
  86. def get_request_direct(): 
  87.   import httplib 
  88.   httplib.HTTPConnection.debuglevel = 1 
  89.   request = urllib2.Request("http://www.google.com"
  90.   request.add_header("Accept", "text/html,*/*"
  91.   request.add_header("Connection", "Keep-Alive"
  92.   opener = urllib2.build_opener() 
  93.   f = opener.open(request) 
  94.   print f.url 
  95.   print f.headers.dict 
  96.   print len(f.read()) 
  97.  
  98. if __name__ == "__main__"
  99.   use_urllib2() 
  100.   get_request() 
  101.   get_request_direct() 
  102.   use_proxy() 
  103.   hand_cookie() 
 

        Python urllib2遞歸抓取某個網站下圖片       

        分類:            Python筆記 92人閱讀 評論(0) 收藏 舉報

 

需求:

抓取某個網站下圖片

可定義 圖片保存路徑,最小圖片大小域值,遍歷深度,是否遍歷到外站,抓取並下載圖片

 

使用庫:

urllib     http://docs.python.org/library/urllib.html【下載】

urllib2  http://docs.python.org/library/urllib2.html【抓取】

urlparse  http://docs.python.org/library/urlparse.html【url切分用到】

sgmllib  http://docs.python.org/library/sgmllib.html【html解析用到】

 

代碼:

[python] view plain copy print ?
  1. #!/usr/bin/python 
  2. # -*- coding:utf-8 -*- 
  3. # author: wklken 
  4. # 2012-03-17 wklken@yeah.net 
  5. #1實現url解析 #2實現圖片下載 #3優化重構 
  6. #4多線程 尚未加入 
  7.  
  8. import os,sys,urllib,urllib2,urlparse 
  9. from sgmllib import SGMLParser  
  10.  
  11. img = [] 
  12. class URLLister(SGMLParser): 
  13.   def reset(self): 
  14.     SGMLParser.reset(self
  15.     self.urls=[] 
  16.     self.imgs=[] 
  17.   def start_a(self, attrs): 
  18.     href = [ v for k,v in attrs if k=="href"and v.startswith("http")] 
  19.     if href: 
  20.       self.urls.extend(href) 
  21.   def start_img(self, attrs): 
  22.     src = [ v for k,v in attrs if k=="src"and v.startswith("http") ] 
  23.     if src: 
  24.       self.imgs.extend(src) 
  25.  
  26.  
  27. def get_url_of_page(url, if_img = False): 
  28.   urls = [] 
  29.   try
  30.     f = urllib2.urlopen(url, timeout=1).read() 
  31.     url_listen = URLLister() 
  32.     url_listen.feed(f) 
  33.     if if_img: 
  34.       urls.extend(url_listen.imgs) 
  35.     else
  36.       urls.extend(url_listen.urls) 
  37.   except urllib2.URLError, e: 
  38.     print e.reason 
  39.   return urls 
  40.  
  41. #遞歸處理頁面 
  42. def get_page_html(begin_url, depth, ignore_outer, main_site_domain): 
  43.   #若是設置排除外站 過濾之 
  44.   if ignore_outer: 
  45.     ifnot main_site_domain in begin_url: 
  46.       return 
  47.  
  48.   if depth == 1
  49.     urls = get_url_of_page(begin_url, True
  50.     img.extend(urls) 
  51.   else
  52.     urls = get_url_of_page(begin_url) 
  53.     if urls: 
  54.       for url in urls: 
  55.         get_page_html(url, depth-1
  56.  
  57. #下載圖片 
  58. def download_img(save_path, min_size): 
  59.   print"download begin..." 
  60.   for im in img: 
  61.     filename = im.split("/")[-1
  62.     dist = os.path.join(save_path, filename) 
  63.     #此方式判斷圖片的大小太浪費了 
  64.     #if len(urllib2.urlopen(im).read()) < min_size: 
  65.     #  continue 
  66.     #這種方式先拉頭部,應該好多了,不用再下載一次 
  67.     connection = urllib2.build_opener().open(urllib2.Request(im)) 
  68.     if int(connection.headers.dict['content-length']) < min_size: 
  69.       continue 
  70.     urllib.urlretrieve(im, dist,None
  71.     print"Done: ", filename 
  72.   print"download end..." 
  73.  
  74. if __name__ == "__main__"
  75.   #抓取圖片首個頁面 
  76.   url = "http://www.baidu.com/" 
  77.   #圖片保存路徑 
  78.   save_path = os.path.abspath("./downlaod"
  79.   ifnot os.path.exists(save_path): 
  80.     os.mkdir(save_path) 
  81.   #限制圖片最小必須大於此域值  單位 B 
  82.   min_size = 92 
  83.   #遍歷深度 
  84.   max_depth = 1 
  85.   #是否只遍歷目標站內,即存在外站是否忽略 
  86.   ignore_outer = True 
  87.   main_site_domain = urlparse.urlsplit(url).netloc 
  88.  
  89.   get_page_html(url, max_depth, ignore_outer, main_site_domain) 
  90.  
  91.   download_img(save_path, min_size) 

 

 

 

后續可以優化

1.使用多線程優化下載,目前多層遍歷不夠速度

2.使用BeautifulSoup寫一個版本

3.加入圖形界面......

 

 

2012-03-17

wklken

 

轉載請注明出處:http://blog.csdn.net/wklken


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM