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

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

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

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

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

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

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

Python
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
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()msgversionstatusreasondebuglevelclosed函数,其实一般而言使用read()函数后还需要decode()函数,这里一个巨大的优势就是:返回的网页内容实际上是没有被解码或的,在read()得到内容后通过指定decode()函数参数,可以使用对应的解码方式。


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

Python
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()函数。


转至:https://www.polarxiong.com/archives/python-3-urllib.html