2019年12月16日 星期一

Urllib.request用法簡單介紹


Urllib.request用法簡單介紹




urllib- URL處理模塊

源代碼: Lib / urllib /

urllib 是一個軟件包,收集了幾個用於處理URL的模塊:
               是Python標準庫的一部分,包含 四個子模塊


主要介紹 urllib.request 的一些簡單用法.

首先是 urlopen 函數,用於打開一個 URL:




urllib.request將你的HTTP請求保存為一個``Request``物件。在最簡單的情況下,一個Request物件裡包含你所請求的特定URL。以當前的Request對象作為參數調用``urlopen``返回伺服器對你正在請求的URL的回應。回應是個檔類物件,所以你可以調用如``.read()``等命令。

import urllib.request

req = urllib.request.Request('http://www.voidspace.org.uk')
with urllib.request.urlopen(req) as response:
   the_page = response.read()


# -*- coding:utf-8 -*- 
#獲取並列印google首頁的html
import urllib.request

response=urllib.request.urlopen('http://www.google.com')
html=response.read()

print(html)



urlopen 返回一個類檔對象,可以像檔一樣操作,同時支援一下三個方法:

info()      :返回一個對象,表示遠程服務器返回的頭資訊。
getcode():返回Http狀態碼,如果是http請求,200表示請求成功完成;404表示網址未找到。
geturl()    :返回請求的url地址。

沒有留言:

張貼留言

print(dir(urllib.request.urlopen(url))) 實作

import urllib.request url = 'http://www.baidu.com/' response = urllib.request.urlopen(url) print(type(response)) print(dir(...