urllib模塊
作用
主要用于從網(wǎng)頁上抓取數(shù)據(jù)蟆湖。以及封裝了一些常用的URL編碼解碼函數(shù)
使用方法
最簡(jiǎn)單的使用, 以打開百度為例
import urllib
url = 'http://www.baidu.com'
print urllib.urlopen(url).read()
注意點(diǎn):
- url必須加上協(xié)議頭"http://", 否則會(huì)不起作用玻粪,認(rèn)為是打開本地文件
- urlopen默認(rèn)是get方法, 加上data參數(shù)就是post
使用代理
proxies = {'http': 'http://www.someproxy.com:3128'}
filehandle = urllib.urlopen(some_url, proxies=proxies)
關(guān)于代理隅津,還需要說一點(diǎn)時(shí),使用urllib.open()時(shí)默認(rèn)會(huì)使用系統(tǒng)環(huán)境變量http_proxy
設(shè)置的代理
返回值
urllib.open()的返回值的一些方法與操作本地文件一樣劲室。如
import urllib
url = 'http://www.baidu.com'
res = urllib.urlopen(url)
# 讀取所有內(nèi)容
print res.read()
# 讀取一行內(nèi)容
print res.readline()
# 按行讀取伦仍,返回一個(gè)列表
print res.readlines()
# 讀取文件描述符(類似shell腳本里錯(cuò)誤重定向里的0, 1, 2)
print res.fileno()
# 獲取返回的地址, 請(qǐng)求的鏈接可能被重定向過
print res.geturl()
# 獲取請(qǐng)求獲取的http狀態(tài)碼
print res.getcode()
# 返回請(qǐng)求的headers信息,類似curl -I 命令
print res.info()
下載網(wǎng)頁
import urllib
# 保存網(wǎng)頁內(nèi)容到文件
url = 'http://www.baidu.com'
filename, headers = urllib.urlretrieve(url, '/tmp/baidu.html')
print filename
print headers
# 清理之前調(diào)用urlretrieve的緩存信息
urllib.urlcleanup()
url編碼解碼
對(duì)字符串進(jìn)行URL編碼
# quote對(duì)字符串進(jìn)行編碼
print urllib.quote('abc def') # abc%20def
# safe參數(shù)指定不需要編碼的字符, 默認(rèn)值是'/'
print urllib.quote('http://www.baidu.com') # http%3A//www.baidu.com
print urllib.quote('http://www.baidu.com', safe=':/') # http://www.baidu.com
print urllib.quote('example@foxmail.com', safe=':/') # example%40foxmail.com
# quote_plus跟quote一樣,只是把空格轉(zhuǎn)換成"+"
print urllib.quote_plus('abc def') # abc+def
# unquote對(duì)字符串進(jìn)行解碼, 與quote作用相反
print urllib.unquote("http%3A//www.baidu.com") # http://www.baidu.com
print urllib.unquote_plus("abc+def") # abc def
# urlencode將字典或元祖序列轉(zhuǎn)換成字符串
print urllib.urlencode({"name": 'xxx', 'age': [10, 11]}, doseq=0) # age=%5B10%2C+11%5D&name=xxx
print urllib.urlencode((("name", 'xxx'), ('age', [10,11])))
# doseq參數(shù)表示是否把列表解析為重復(fù)的參數(shù)
print urllib.urlencode({"name": 'xxx', 'age': [10, 11]}, doseq=1) # age=10&age=11&name=xxx
# 查看當(dāng)前使用的代理
print urllib.getproxies()
一些例子
GET請(qǐng)求
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
>>> print f.read()
POST請(qǐng)求
>>> import urllib
>>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
>>> print f.read()
使用代理
>>> import urllib
>>> proxies = {'http': 'http://proxy.example.com:8080/'}
>>> opener = urllib.FancyURLopener(proxies)
>>> f = opener.open("http://www.python.org")
>>> f.read()