python核心類庫 urllib使用詳解

2021-09-08 15:11:45 字數 2148 閱讀 2194

python版本:2.7.15

1.簡單用法urllib.urlopen()

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

開啟乙個url的方法,返回乙個檔案物件,然後可以進行類似檔案物件的操作。

示例**:

# 讀取html頁面的第一行

firstline = googleresponse.readline()

# 就像在操作本地檔案

for line in googleresponse:

print line,

googleresponse.close()

urlopen返回物件提供方法:

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

- info():返回乙個httplib.httpmessage物件,表示遠端伺服器返回的頭資訊

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

- geturl():返回請求的url

2.儲存為檔案urllib.urlretrieve()臨時存放:

filename = urllib.urlretrieve('/')

prtin type(filename)

# prtin filename[0]

# '/tmp/tmp8evljq'

print filename[1]

# 存為本地檔案:

filename = urllib.urlretrieve('/',filename='/home/python/google.html')

print type(filename)

# print filename[0]

# '/home/python/google.html'

print filename[1]

#3.使用urllib實現post方法和get方法

需要用到urllib.urlencode(query)將url中的引數鍵值對以連線符&劃分

get方法:

import urllib

params=urllib.urlencode()

print params

# 'pwd=123456&name=aaron&rem=0'

f=urllib.urlopen("" % params)

print f.read()

post方法:

import urllib

parmas = urllib.urlencode()

f=urllib.urlopen("",parmas)

f.read()

4.其它方法

urllib.urlcleanup()

清除由於urllib.urlretrieve()所產生的快取

urllib.quote(url)和urllib.quote_plus(url)

將url資料獲取之後,並將其編碼,從而適用與url字串中,使其能被列印和被web伺服器接受。

urllib.unquote(url)和urllib.unquote_plus(url)

與urllib.quote(url)和urllib.quote_plus(url)函式相反。

done!

核心類庫 常用類庫

math類 math.abs 傳入引數的絕對值 math.max min 比較傳入的多個引數的最大 最小值 math.random 初始值是隨機生成0 1之間的double型別的正值 math.round 對傳入的float double值四捨五入 math.floor 返回值小於或等於傳入的數字的...

爬蟲 Python爬蟲學習筆記之Urllib庫

1.urllib.request開啟和讀取url 2.urllib.error包含urllib.request各種錯誤的模組 3.urllib.parse解析url 4.urllib.robotparse解析 robots.txt檔案 傳送get請求 引入urlopen庫 用於開啟網頁 from u...

python核心 元類

type動態的建立乙個類 type 類名 父類 test type test t1.test type t1 結果為 main testtype建立乙個帶有方法的類 def printnum self print num d self.num test2 type test2 t1 test2 t1...