首页 新闻 会员 周边

python 中的urllib2.urlopen()方法

0
悬赏园豆:10 [待解决问题]

  在python中,urllib2中的urlopen()方法可以这样用:

response=urllib2.urlopen("http://www.baidu.com")
html=response.read()

也可以这样用:先创建一个Request对象

request=urllib2.Request("http://www.baidu.com")
response=urllib2.urlopen(request)
html=response.read()

查看urllib2.urlopen()方法:

urlopen(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)

其中并没有Request类型的参数,但是为什么可以这样用呢?

mcfer的主页 mcfer | 初学一级 | 园豆:144
提问于:2015-03-15 18:24
< >
分享
所有回答(2)
0

有没有人知道呢?

mcfer | 园豆:144 (初学一级) | 2015-03-15 19:46
0

从urlopen详细参数中看,好像是没有与Request对象相关的参数,但是我找了找urllib2的官方API介绍,你可以看看,再加上自己的一些理解,不知道是否正确。

urlopen(url, data=None) -- Basic usage is the same as original urllib.  pass the url and optionally data to post to an HTTP URL, and
get a file-like object back.  One difference is that you can also pass a Request instance instead of URL. 

urllib2.urlopen基础的用法跟urllib.urlopen是一样的,都是以类文件对象返回,不同的就是urllib2可以在urlopen中传入Request实体对象来代替URL。

Request -- An object that encapsulates the state of a request.  The state can be as simple as the URL.  It can also include extra HTTP headers, e.g. a User-Agent.

request请求返回的状态封装到一个实体中,这个实体就是Request实体/对象,这个返回的状态其本质还是URL,只是换了一种形态。

west_Tang风 | 园豆:201 (菜鸟二级) | 2016-01-29 16:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册