Python3:urllib中urlopen()函数新特点

转自:http://www.polarxiong.com/archives/python-3-urllib.html

因为用Python2爬网页被编码问题逼疯了,迫不得已用上了Python3,用上Python3才发现真是个新世界,简直太给力了。

Python2的urllib、urllib2在Python3中集合成了urllib模块,这样逻辑清晰了不少。urllib库包含下面几个内容:

urllib.request
urllib.error
urllib.parse
urllib.robotparser

最主要的当然就是request模块了,最常用到的函数就是:

urllib.request.urlopen(url,data=None[,timeout],*,cafile=None,capath=None,cadefault=False,context=None)

这里需要注意的是这个函数和Python2中的urllib、urllib2模块中函数区别很大。

Python2中urlopen()函数返回的是addinfourl对象:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import urllib
>>> s=urllib.urlopen('http://www.baidu.com')
>>> print s
<addinfourl at 45887360 whose fp = <socket._fileobject object at 0x02BB6BF0>>

addinfourl对象实际上是一个类似于文件的对象,大概包括read()、readline()、readlines()、fileno()、close()、info()、getcode()和geturl()函数,其实这里隐藏了一个巨大的缺陷:返回的网页内容实际上已经被默认解码了,而不是由自己决定如何解码。

Python3中urlopen()函数返回的是http.client.HTTPResponse对象:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import urllib.request
>>> s=urllib.request.urlopen('http://www.baidu.com')
>>> print(s)
<http.client.HTTPResponse object at 0x00000000034AD048>

http.client.HTTPResponse对象大概包括read()、readinto()、getheader()、getheaders()、fileno()、msg、version、status、reason、debuglevel和closed函数,其实一般而言使用read()函数后还需要decode()函数,这里一个巨大的优势就是:返回的网页内容实际上是没有被解码或的,在read()得到内容后通过指定decode()函数参数,可以使用对应的解码方式。

urllib.request.urlopen()使用示例:

import urllib.request

s = urllib.request.urlopen('http://www.njust.edu.cn')
d = s.read().decode('gbk')
print(d)

gbk编码的网页使用’gbk’解码,UTF-8编码的就是’utf-8’了,这样几乎可以避免所有的Python2中编码错误的问题!

注意urlopen()函数不接受自定义header,所以有需求还需要配合urllib.request.Request()函数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值