python是蜘蛛之王,蜘蛛離不開urllib。 urllib2 是urllib 的另一個版本,有很多改進。 聽說內部代碼也好了很多。
urllib2是python自帶的一個訪問網頁和本地文件的庫。 簡單使用如下:
訪問一個網址:
~~~
import urllib2
f=urllib2.urlopen("http://www.jeapedu.com")
buf = f.read()
~~~
讀一個本地文件:
~~~
import urllib2
f=urllib2.urlopen('file:./a.txt')
buf=f.read()
~~~
如何獲取庫有那些函數或者類:
~~~
>>> dir(f)
['__doc__', '__init__', '__iter__', '__module__', '__repr__', 'close', 'code', 'fileno', 'fp', 'getcode', 'geturl', 'headers', 'info', 'next', 'read', 'readline', 'readlines', 'url']
>>>
~~~
### 中文地址解析:[?](http://uliweb.clkg.org/tutorial/view_chapter/172#title_0-0-1)
~~~
h4 = u'http://www.baidu.com?w=測試'
h4=h4.encode('utf-8')
urllib2.urlopen(h4)
~~~
最好用正確的編碼轉換一下。 上面的例子如果不用轉換的函數處理一下網址,會導致urlopen 失敗。
### 分類操作[?](http://uliweb.clkg.org/tutorial/view_chapter/172#title_0-0-2)
FTP
~~~
handler = urllib2.FTPHandler()
request = urllib2.Request(url='ftp://ftp.ubuntu.com/')
opener = urllib2.build_opener(handler)
f = opener.open(request)
print f.read()
~~~
如果需要用戶名和密碼:
~~~
urllib2.Request(url='ftp://用戶名:密碼@ftp地址/')
~~~
HTTP
~~~
handler = urllib2.HTTPHandler()
request = urllib2.Request(url='http://ftp.ubuntu.com/')
opener = urllib2.build_opener(handler)
f = opener.open(request)
print f.read()
~~~
支持 headers
~~~
#coding=utf-8
import urllib2
request = urllib2.Request(url='http://192.168.2.201:8000/hd.txt')
request.add_header('Accept-encoding', 'gzip')
f = urllib2.urlopen(request)
print f.read()
~~~
- Python爬蟲入門
- (1):綜述
- (2):爬蟲基礎了解
- (3):Urllib庫的基本使用
- (4):Urllib庫的高級用法
- (5):URLError異常處理
- (6):Cookie的使用
- (7):正則表達式
- (8):Beautiful Soup的用法
- Python爬蟲進階
- Python爬蟲進階一之爬蟲框架概述
- Python爬蟲進階二之PySpider框架安裝配置
- Python爬蟲進階三之Scrapy框架安裝配置
- Python爬蟲進階四之PySpider的用法
- Python爬蟲實戰
- Python爬蟲實戰(1):爬取糗事百科段子
- Python爬蟲實戰(2):百度貼吧帖子
- Python爬蟲實戰(3):計算大學本學期績點
- Python爬蟲實戰(4):模擬登錄淘寶并獲取所有訂單
- Python爬蟲實戰(5):抓取淘寶MM照片
- Python爬蟲實戰(6):抓取愛問知識人問題并保存至數據庫
- Python爬蟲利器
- Python爬蟲文章
- Python爬蟲(一)--豆瓣電影抓站小結(成功抓取Top100電影)
- Python爬蟲(二)--Coursera抓站小結
- Python爬蟲(三)-Socket網絡編程
- Python爬蟲(四)--多線程
- Python爬蟲(五)--多線程續(Queue)
- Python爬蟲(六)--Scrapy框架學習
- Python爬蟲(七)--Scrapy模擬登錄
- Python筆記
- python 知乎爬蟲
- Python 爬蟲之——模擬登陸
- python的urllib2 模塊解析
- 蜘蛛項目要用的數據庫操作
- gzip 壓縮格式的網站處理方法
- 通過瀏覽器的調試得出 headers轉換成字典
- Python登錄到weibo.com
- weibo v1.4.5 支持 RSA協議(模擬微博登錄)
- 搭建Scrapy爬蟲的開發環境
- 知乎精華回答的非專業大數據統計
- 基于PySpider的weibo.cn爬蟲
- Python-實現批量抓取妹子圖片
- Python庫
- python數據庫-mysql
- 圖片處理庫PIL
- Mac OS X安裝 Scrapy、PIL、BeautifulSoup
- 正則表達式 re模塊
- 郵件正則
- 正則匹配,但過濾某些字符串
- dict使用方法和快捷查找
- httplib2 庫的使用