Python库urllib与urllib2主要区别分析

yipeiwu_com4年前Python基础

作为一个Python菜鸟,之前一直懵懂于urllib和urllib2,以为2是1的升级版。今天看到老外写的一篇《Python: difference between urllib and urllib2》才明白其中的区别

You might be intrigued by the existence of two separate URL modules in Python -urllib and urllib2. Even more intriguing: they are not alternatives for each other. So what is the difference between urllib and urllib2, and do we need them both?

你可能对于Python中两个独立存在的-urllib2和-urllib2感到好奇。更有趣的是:它们并不是可以相互代替的。那么这两个模块间的区别是什么,并且这两个我们都需要吗?

urllib and  urllib2are both Python modules that do URL request related stuff but offer different functionalities. Their two most significant differences are listed below:

urllib 和urllib2都是接受URL请求的相关模块,但是提供了不同的功能。两个最显著的不同如下:

•urllib2 can accept a Request object to set the headers for a URL request,urllib accepts only a URL. That means, you cannot masquerade your User Agent string etc.

urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,你不可以伪装你的User Agent字符串等。

•urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function. This is one of the reasons why urllib is often used along with urllib2.

urllib提供urlencode方法用来GET查询字符串的产生,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。 

 For other differences between urllib and urllib2 refer to their documentations, the links are given in the References section.
Tip: if you are planning to do HTTP stuff only, check out httplib2, it is much better than httplib or urllib or urllib2.

提示:如果你仅做HTTP相关的,看一下httplib2,比其他几个模块好用。

相关资料

这里还有个类似的问答:urllib urllib2 what is the difference ?

stackoverflow上也有:Should I use urllib or urllib2?

Python Docs

相关文章

PyQt5实现拖放功能

PyQt5实现拖放功能

在这节教程中,我们将探讨PyQt5中的拖放操作。 在计算机图形用户界面(GUI)中,拖放是在某个虚拟对象上点击并拖动到另一个位置或虚拟对象上的操作。它通常用于调用多个动作,或为两个抽象对...

Python可视化mhd格式和raw格式的医学图像并保存的方法

Python可视化mhd格式和raw格式的医学图像并保存的方法

mhd格式的文件里面包含的是raw图像的一些头信息,比如图片大小,拍摄日期等等,那么如何可视化图像呢? import cv2 import SimpleITK as sitk imp...

详解Django+Uwsgi+Nginx 实现生产环境部署

uwsgi介绍 uWSGI是一个Web服务器,它实现了WSGI协议、uwsgi、http等协议。Nginx中HttpUwsgiModule的作用是与uWSGI服务器进行交换。 要注意...

python实现将html表格转换成CSV文件的方法

本文实例讲述了python实现将html表格转换成CSV文件的方法。分享给大家供大家参考。具体如下: 使用方法:python html2csv.py *.html 这段代码使用了 HTM...

Python字典中的键映射多个值的方法(列表或者集合)

一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典: d = {...