urllib.request.urlopen() 有什么作用? [英] what does urllib.request.urlopen() do?
问题描述
在 python 3 中,urllib.request 模块中的 urlopen 函数是否检索 URL 的目标,或者只是打开到 URL 的连接作为文件句柄,或者我完全丢失了它?我想了解它是如何工作的.
In python 3 does urlopen function from urllib.request module retrieve the target of the URL or just open a connection to the URL as a file handle or have i completely lost it ? I would like to understand how it works.
基本上我想找到从 URL 下载文件所花费的时间.我该怎么做?
Basically i want to find the time taken to download a file from a URL. how do i go about it ?
这是我的代码:
版本 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,可以是字符串,也可以是请求对象.
Open the URL url, which can be either a string or a Request object.
...
这个函数返回一个类文件对象,并带有三个额外的方法:
This function returns a file-like object with three additional methods:
- geturl() — 返回检索到的资源的 URL,通常用于确定是否遵循重定向
- info() — 以 mimetools.Message 实例的形式返回页面的元信息,例如标头(参见 HTTP 标头快速参考)
- getcode() — 返回响应的 HTTP 状态代码.
另请注意,从 Python 3.0 开始,urllib.request.urlopen()
和 urllib.urlopen()
是等效的.
Also note that as of Python 3.0, urllib.request.urlopen()
and urllib.urlopen()
are equivalent.
EDIT 所以,要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
这篇关于urllib.request.urlopen() 有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!