区别

  1. urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib仅可以接受URL。这意味着,用urllib时不可以伪装User Agent字符串等。
  2. urllib提供urlencode方法用来encode发送的data,而urllib2没有。这是为何urllib常和urllib2一起使用的原因。

urllib

1 urllib.urlopen(url[,data[,proxies]])

打开一个url的方法,返回一个文件对象

>>> req = urllib.urlopen('http://www.baidu.com')
>>> req.readline() # 读取一行
'<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="\xe7\x99\xbe\xe5\xba\xa6\xe6\x90\x9c\xe7\xb4\xa2" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><link rel="dns-prefetch" href="//b1.bdstatic.com"/><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>\n'
urlopen返回对象提供方法:
- read() , readline() ,readlines() , fileno() , close():这些方法的使用方式与文件对象完全一样
- info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url

2 urllib.urlretrieve(url[,filename[,reporthook[,data]]])

urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。

urlretrieve()返回一个二元组(filename,mine_hdrs)

>>> filename = urllib.urlretrieve('http://www.baidu.com')
>>> type(filename)
<type 'tuple'>
>>> filename
('/tmp/tmphngDjh', <httplib.HTTPMessage instance at 0x7fd5e03ea248>)
>>> filename = urllib.urlretrieve('http://www.baidu.com/',filename='/tmp/baidu')
>>> type(filename)
<type 'tuple'>
>>> filename
('/tmp/baidu', <httplib.HTTPMessage instance at 0x7fd5e03dbb48>)

3 urllib.urlcleanup()

清除由于urllib.urlretrieve()所产生的缓存

4 urllib.quote(url)和urllib.quote_plus(url)

将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受。

>>> urllib.quote('http://www.baidu.com')
'http%3A//www.baidu.com'
>>> urllib.quote_plus('http://www.baidu.com')
'http%3A%2F%2Fwww.baidu.com'

5 urllib.unquote(url)和urllib.unquote_plus(url)

与4的函数相反。

6 urllib.urlencode(query)

将URL中的键值对以连接符&划分

GET方法

>>> import urllib
>>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> params
'eggs=2&bacon=0&spam=1'
>>> f=urllib.urlopen("http://python.org/query?%s" % params)
>>> print f.read()

POST方法

>>> import urllib
>>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0})
>>> f=urllib.urlopen("http://python.org/query", parmas)
>>> f.read()

urllib2

http://www.codefrom.com/paper/深入理解urllib、urllib2及requests

http://zhuoqiang.me/python-urllib2-usage.html

1 urllib2.urlopen()

>>> import urllib2
>>> url = 'http://www.baidu.com'
>>> req = urllib2.urlopen(url)
>>> req.readline()
'<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="\xe7\x99\xbe\xe5\xba\xa6\xe6\x90\x9c\xe7\xb4\xa2" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><link rel="dns-prefetch" href="//b1.bdstatic.com"/><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>\n'

2 urllib2.Request()

>>> url = 'http://www.baidu.com'
>>> req = urllib2.Request(url)
>>> resp = urllib2.urlopen(req) #使用对象
>>> resp.readline()
'<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=Edge"><meta content="always" name="referrer"><meta name="theme-color" content="#2932e1"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /><link rel="search" type="application/opensearchdescription+xml" href="/content-search.xml" title="\xe7\x99\xbe\xe5\xba\xa6\xe6\x90\x9c\xe7\xb4\xa2" /><link rel="icon" sizes="any" mask href="//www.baidu.com/img/baidu.svg"><link rel="dns-prefetch" href="//s1.bdstatic.com"/><link rel="dns-prefetch" href="//t1.baidu.com"/><link rel="dns-prefetch" href="//t2.baidu.com"/><link rel="dns-prefetch" href="//t3.baidu.com"/><link rel="dns-prefetch" href="//t10.baidu.com"/><link rel="dns-prefetch" href="//t11.baidu.com"/><link rel="dns-prefetch" href="//t12.baidu.com"/><link rel="dns-prefetch" href="//b1.bdstatic.com"/><title>\xe7\x99\xbe\xe5\xba\xa6\xe4\xb8\x80\xe4\xb8\x8b\xef\xbc\x8c\xe4\xbd\xa0\xe5\xb0\xb1\xe7\x9f\xa5\xe9\x81\x93</title>\n'

3 urllib2.Request(url[, data][, headers][, originreqhost][, unverifiable])

import urllib, urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' }
data = urllib.urlencode(values)
req = urllib2.Request(url, data) #send post
resp = urllib2.urlopen(req)
resp.read()

5 header

import urllib, urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' }
headers = { 'User-Agent' : user_agent } data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
resp = urllib2.urlopen(req)
resp.read()

6 add_header(key, val)

import urllib2

req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resq = urllib2.urlopen(req)

7 PUT和DELETE方法

import urllib2

request = urllib2.Request(uri, data=data)
request.get_method = lambda: 'PUT' # or 'DELETE'
response = urllib2.urlopen(request)

注意

1. 如果只是单纯的下载或者显示下载进度,不对下载后的内容做处理等,比如下载图片,css,js文件等,可以用urlilb.urlretrieve()
2. 如果是下载的请求需要填写表单,输入账号,密码等,建议用urllib2.urlopen(urllib2.Request())
3. 在对字典数据编码时候,用到的是urllib.urlencode()

python urllib urllib2的更多相关文章

  1. Python +urllib+urllib2 带数据的post请求实例

    #coding:utf-8 ''' Created on 2017年11月2日 @author: li.liu ''' import urllib import urllib2 import re f ...

  2. python中urllib, urllib2,urllib3, httplib,httplib2, request的区别

    permike原文python中urllib, urllib2,urllib3, httplib,httplib2, request的区别 若只使用python3.X, 下面可以不看了, 记住有个ur ...

  3. Python:urllib和urllib2的区别(转)

    原文链接:http://www.cnblogs.com/yuxc/ 作为一个Python菜鸟,之前一直懵懂于urllib和urllib2,以为2是1的升级版.今天看到老外写的一篇<Python: ...

  4. Python urllib和urllib2模块学习(一)

    (参考资料:现代魔法学院 http://www.nowamagic.net/academy/detail/1302803) Python标准库中有许多实用的工具类,但是在具体使用时,标准库文档上对使用 ...

  5. python urllib和urllib2 区别

    python有一个基础的库叫httplib.httplib实现了HTTP和HTTPS的客户端协议,一般不直接使用,在python更高层的封装模块中(urllib,urllib2)使用了它的http实现 ...

  6. python通过get方式,post方式发送http请求和接收http响应-urllib urllib2

    python通过get方式,post方式发送http请求和接收http响应-- import urllib模块,urllib2模块, httplib模块 http://blog.163.com/xyc ...

  7. python中 urllib, urllib2, httplib, httplib2 几个库的区别

    转载 摘要: 只用 python3, 只用 urllib 若只使用python3.X, 下面可以不看了, 记住有个urllib的库就行了 python2.X 有这些库名可用: urllib, urll ...

  8. 人生苦短之Python的urllib urllib2 requests

    在Python中涉及到URL请求相关的操作涉及到模块有urllib,urllib2,requests,其中urllib和urllib2是Python自带的HTTP访问标准库,requsets是第三方库 ...

  9. HTTP Header Injection in Python urllib

    catalogue . Overview . The urllib Bug . Attack Scenarios . 其他场景 . 防护/缓解手段 1. Overview Python's built ...

随机推荐

  1. python3读取文件

    #coding:utf-8 rfile = open('test.txt','r') str=[] for x in rfile: str = x.split(',') for x in str: p ...

  2. Spark 1.4连接mysql诡异的问题及解决

    在spark-default.conf文件中明明配置了mysql的数据源连接 随后启动spark-shell 执行如下测试代码: import org.apache.spark.{SparkConte ...

  3. IGS_学习笔记06_IREP发布客户化集成接口为Web Service(案例)

    2015-01-03 Created By BaoXinjian

  4. UVA1347 旅游(二维递归DP)

    旅游 [题目链接]旅游 [题目类型]DP &题解: 紫书P269 代码很简单,但思路很难.很难能想到要把一个圈分成2条线段,很难想到d(i,j)表示的是已经走过max(i,j)还需要的距离值, ...

  5. [实变函数]2.2 聚点 (cluster point), 内点 (interior point), 界点 (boundary point)

    设 $E\subset \bbR^n, P_0\in \bbR^n$. 1 若 $\exists\ U(P_0)\subset E$, 则称 $P_0$ 为 $E$ 的内点 (interior poi ...

  6. ylbtech-Recode(记录)-数据库设计

    ylbtech-dbs:ylbtech-Recode(记录)-数据库设计 -- =============================================-- DatabaseName ...

  7. iconv 批量修改文件编码

    iconv_shell.sh #!/bin/bash "];then echo "Usage: `basename $0` dir filter" exit fi dir ...

  8. Jquery插件收藏

    1.带小图标的多级菜单导航 演示地址:http://js.itivy.com/memu/sample.html 下载地址:http://js.itivy.com/?p=100 效果图:  推荐一个自己 ...

  9. c# WMI获取机器硬件信息(硬盘,cpu,内存等)

    using System; using System.Collections.Generic; using System.Globalization; using System.Management; ...

  10. 90、 Android UI模板设计

    第一步:自定义xml属性 新建一个android项目,在values文件夹中新建一个atts.xml的文件,在这个xml文件中声明我们一会在使用自定义控件时候需要指明的属性.atts.xml < ...