簡體   English   中英

urllib.request.urlopen()有什么作用?

[英]what does urllib.request.urlopen() do?

在python 3中,來自urllib.request模塊的urlopen函數檢索URL的目標,或者只是打開與URL的連接作為文件句柄還是我完全丟失了它? 我想了解它是如何工作的。

基本上我想找到從URL下載文件所花費的時間。 我該怎么辦呢?

這是我的代碼:

版本1

import urllib
import time

start = time.time()
with urllib.request.urlopen('http://mirror.hactar.bz/lastsync') as f:
    lastsync = f.read() #Do i need this line if i dont care about the data
    end = time.time()
duration = end - start

版本2

import urllib
import time

with urllib.request.urlopen('http://mirror.hactar.bz/lastsync') as f:
    start = time.time()
    lastsync = f.read() #Does this line do the actual data retrieval ?
    end = time.time()
duration = end - start

來自文檔

打開URL url,可以是字符串或Request對象。

...

此函數返回一個類似文件的對象,其中包含三個附加方法:

  • geturl() - 返回檢索到的資源的URL,通常用於確定是否遵循重定向
  • info() - 以mimetools.Message實例的形式返回頁面的元信息,例如標題(請參閱HTTP標題的快速參考)
  • getcode() - 返回響應的HTTP狀態代碼。

另請注意,從Python 3.0開始, urllib.request.urlopen()urllib.urlopen()是等效的。

編輯所以, time

# urllib.request for < python 3.0
import urllib
import time

start = time.time()

# urllib.request.urlopen() for < python 3.0
response = urllib.urlopen('http://example.com/')
data = response.read() # a `bytes` object
end = time.time()

duration = end - start

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM