2019独角兽企业重金招聘Python工程师标准>>>

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://john88wang.blog.51cto.com/2165294/1441495

一 urlib模块

利用urllib模块可以打开任意个url。

  1. urlopen() 打开一个url返回一个文件对象,可以进行类似文件对象的操作。

In [308]: import urllib
In [309]: file=urllib.urlopen('
In [310]: file.readline()
Out[310]: '<!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"><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

可以用read(),readlines(),fileno(),close()这些函数

In [337]: file.info()
Out[337]: <httplib.HTTPMessage instance at 0x2394a70>In [338]: file.getcode()
Out[338]: 200In [339]: file.geturl()
Out[339]: 'http://www.baidu.com/'

2.urlretrieve() 将url对应的html页面保存为文件

In [404]: filename=urllib.urlretrieve('http://www.baidu.com/',filename='/tmp/baidu.html')In [405]: type (filename)
Out[405]: <type 'tuple'>In [406]: filename[0]
Out[406]: '/tmp/baidu.html'In [407]: filename
Out[407]: ('/tmp/baidu.html', <httplib.HTTPMessage instance at 0x23ba878>)In [408]: filename[1]
Out[408]: <httplib.HTTPMessage instance at 0x23ba878>

3.urlcleanup()  清除由urlretrieve()产生的缓存

In [454]: filename=urllib.urlretrieve('http://www.baidu.com/',filename='/tmp/baidu.html')In [455]: urllib.urlcleanup()

4.urllib.quote()和urllib.quote_plus() 将url进行编码

In [483]: urllib.quote('http://www.baidu.com')
Out[483]: 'http%3A//www.baidu.com'In [484]: urllib.quote_plus('http://www.baidu.com')
Out[484]: 'http%3A%2F%2Fwww.baidu.com'

5.urllib.unquote()和urllib.unquote_plus() 将编码后的url解码

In [514]: urllib.unquote('http%3A//www.baidu.com')
Out[514]: 'http://www.baidu.com'In [515]: urllib.unquote_plus('http%3A%2F%2Fwww.baidu.com')
Out[515]: 'http://www.baidu.com'

6.urllib.urlencode() 将url中的键值对以&划分,可以结合urlopen()实现POST方法和GET方法

In [560]: import urllib
In [561]: params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0}) ]
In [562]: f=urllib.urlopen("http://python.org/query?%s" %params)
In [563]: f.readline()
Out[563]: '<!doctype html>\n'
In [564]: f.readlines()
Out[564]: ['<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->\n','<!--[if IE 7]>      <html class="no-js ie7 lt-ie8 lt-ie9">          <![endif]-->\n', '<!--[if IE 8]>      <html class="no-js ie8 lt-ie9">                 <![endif]-->\n', '<!--[if gt IE 8]><!--><html class="no-js" lang="en" dir="ltr">  <!--<![endif]-->\n','\n',

二  urllib2模块

urllib2比urllib多了些功能,例如提供基本的认证,重定向,cookie等功能

https://docs.python.org/2/library/urllib2.html

https://docs.python.org/2/howto/urllib2.html

In [566]: import urllib2In [567]: f=urllib2.urlopen('http://www.python.org/')In [568]: print f.read(100)
--------> print(f.read(100))
<!doctype html>
<!--[if lt IE 7]>   <html class="no-js ie6 lt-ie7 lt-ie8 lt-ie9">   <![endif]-->

打开python的官网并返回头100个字节内容

HTTP基于请求和响应,客户端发送请求,服务器响应请求。urllib2使用一个Request对象代表发送的请求,调用urlopen()打开Request对象可以返回一个response对象。reponse对象是一个类似文件的对象,可以像文件一样进行操作

In [630]: import urllib2In [631]: req=urllib2.Request('http://www.baidu.com')In [632]: response=urllib2.urlopen(req)In [633]: the_page=response.read()In [634]: the_page
Out[634]: '<!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"><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.

通常情况下需要向一个url以POST的方式发送数据。

In [763]: import urllibIn [764]: import urllib2In [765]: url='http://xxxxxx/login.php'In [766]: values={'ver' : '1.7.1', 'email' : 'xxxxx', 'password' : 'xxxx', 'mac' : '111111111111'}In [767]: data=urllib.urlencode(values)In [768]: req=urllib2.Request(url,data)In [769]: response=urllib2.urlopen(req)In [770]: the_page=response.read()In [771]: the_page

如果不使用urllib2.Request()发送data参数,urllib2使用GET请求,GET请求和POST请求差别在于POST请求常有副作用,POST请求会通过某些方式改变系统的状态。也可以通过GET请求发送数据。

In [55]: import urllib2In [56]: import urllibIn [57]: url='http://xxx/login.php'In [58]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxx'}In [59]: data=urllib.urlencode(values)In [60]: full_url=url + '?' + dataIn [61]: the_page=urllib2.urlopen(full_url)In [63]: the_page.read()
Out[63]: '{"result":0,"data":0}'

默认情况下,urllib2使用Python-urllib/2.6 表明浏览器类型,可以通过增加User-Agent HTTP头

In [107]: import urllibIn [108]: import urllib2In [109]: url='http://xxx/login.php'In [110]: user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'In [111]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxxx'}In [112]: headers={'User-Agent' : user_agent}In [114]: data=urllib.urlencode(values)In [115]: req=urllib2.Request(url,data,headers)In [116]: response=urllib2.urlopen(req)In [117]: the_page=response.read()In [118]: the_page

当给定的url不能连接时,urlopen()将报URLError异常,当给定的url内容不能访问时,urlopen()会报HTTPError异常

#/usr/bin/pythonfrom urllib2 import Request,urlopen,URLError,HTTPError
req=Request('http://10.10.41.42/index.html')
try:response=urlopen(req)
except HTTPError as e:print 'The server couldn\'t fulfill the request.'print 'Error code:',e.codeexcept URLError as e:print 'We failed to fetch a server.'print 'Reason:',e.reason
else:print "Everything is fine"

这里需要注意的是在写异常处理时,HTTPError必须要写在URLError前面

#/usr/bin/pythonfrom urllib2 import Request,urlopen,URLError,HTTPError
req=Request('http://10.10.41.42')
try:response=urlopen(req)except URLError as e:if hasattr(e,'reason'):print 'We failed to fetch a server.'print 'Reason:',e.reasonelif hasattr(e,'code'):print 'The server couldn\'t fulfill the request.'print 'Error code:',e.code
else:print "Everything is fine"

hasattr()函数判断一个对象是否有给定的属性

使用urllib2模块登录需要基本认证的页面

登录RabbitMQ的管理页面需要进行用户名和密码验证。

In [63]: url='http://172.30.25.179:15672/api/aliveness-test/%2f'In [64]: username='guest'In [65]: password='guest'In [66]: mgr=urllib2.HTTPPasswordMgrWithDefaultRealm()In [67]: s=mgr.add_password(None,url,username,password)In [68]: handler=urllib2.HTTPBasicAuthHandler(mgr)In [69]: opener=urllib2.build_opener(handler)In [70]: opener.open(url).read()
Out[70]: '{"status":"ok"}'json.loads(opener.open(url).read())

参考文档:

https://docs.python.org/2/library/urllib2.html#module-urllib2

本文出自 “Linux SA  John” 博客,请务必保留此出处http://john88wang.blog.51cto.com/2165294/1441495

转载于:https://my.oschina.net/airship/blog/645783

Python学习之urlib模块和urllib2模块学习相关推荐

  1. python下载网页中的pdf文件_【Python】Python的urllib模块、urllib2模块批量进行网页下载文件...

    由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载.正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Python的url ...

  2. python批量下载网页文件夹_Python的urllib模块、urllib2模块批量进行网页下载文件...

    由于需要从某个网页上下载一些PDF文件,但是需要下载的PDF文件有几百个,所以不可能用人工点击来下载.正好Python有相关的模块,所以写了个程序来进行PDF文件的下载,顺便熟悉了Python的url ...

  3. 洗礼灵魂,修炼python(54)--爬虫篇—urllib2模块

    urllib2 1.简介 urllib2模块定义的函数和类用来获取URL(主要是HTTP的),他提供一些复杂的接口用于处理: 基本认证,重定向,Cookies等.urllib2和urllib差不多,不 ...

  4. python2 urllib模块_python urllib2模块

    与urllib的区别 Python的urllib和urllib2模块都做与请求URL相关的操作: 3.x的版本urllib与urllib2已经合并为一个urllib库: 2.7的版本urllib与ur ...

  5. Python爬虫----网页下载器和urllib2模块及对应的实例

    网页下载器:将互联网上URL对应的网页下载到本地的工具,是爬虫的核心组件 urllib2下载网页的三种方法 对应实例代码如下: #coding:utf8import urllib2 url = 'ht ...

  6. Python:urllib2模块Handler处理器 和 自定义Opener

    Handler处理器 和 自定义Opener opener是 urllib2.OpenerDirector 的实例,我们之前一直都在使用的urlopen,它是一个特殊的opener(也就是模块帮我们构 ...

  7. 【Python】Python的urllib模、urllib2模块的网络下载文件

    因为需要从一些下载一个页PDF文件.但是需要下载PDF有数百个文件,这是不可能用人工点击下载.只是Python有相关模块,所以写一个程序PDF文件下载,顺便熟悉Python的urllib模块和ulrl ...

  8. python模块下载1002python模块下载_【Python】Python的urllib模、urllib2模块的网络下载文件...

    因为需要从一些下载一个页PDF文件.但是需要下载PDF有数百个文件,这是不可能用人工点击下载.只是Python有相关模块,所以写一个程序PDF文件下载,顺便熟悉Python的urllib模块和ulrl ...

  9. python2 urllib模块_python urllib与urllib2模块用法教程

    python urllib与urllib2模块用法 urllib 和urllib2都是接受URL请求的相关模块,但是提供了不同的功能. urllib提供urlencode方法用来GET查询字符串的产生 ...

最新文章

  1. Database Appliance并非Mini版的Exadata-还原真实的Oracle Unbreakable Database Appliance
  2. vivo是安卓手机吗_vivo手机更新安卓9.0!4款产品尝鲜:有你的吗?
  3. [转].NET牛人应该知道些什么
  4. python中的成员运算符是干嘛的_在Python中使用成员运算符的示例
  5. c++ GUI轻量工具包FLTK介绍 (1)
  6. R语言绘图—一键添加显著性
  7. c 语言实现链表反转(超详细,有手就行)
  8. 密码系列-Base32
  9. 在linux下如何修改DNS地址
  10. ​TCP和UDP的135、137、138、139、445端口的作用?​
  11. hdu 5755 Gambler Bo 高斯消元
  12. 2013硕士毕业生薪资待遇
  13. R 编程中的 LOOCV(留一法交叉验证)
  14. 三菱服务器显示003C,三菱gps-3电梯开关门特慢门机板显示c.是哪里问题?
  15. Go 与 C++ 的对比和比较
  16. 华为10大物联网解决方案,畅想未来智慧生活
  17. 【英语阅读】经济学人 | 零售商纷纷撤离商业街之际,宜家为何反其道而行之?
  18. 家用计算机cpu,年终聊装机 主流家用电脑怎么选CPU?
  19. ADM2483的原理图
  20. idea mac 查询方法被调用_Mac Idea你不知道的秘密

热门文章

  1. 计划用php写一个七牛文件上传小工具
  2. mongodb java driver 聚合框架
  3. Linux下搭建lamp论坛(phpwind+wordpress+discus)
  4. 使用ArcGIS Engine连接ArcIMS feature Service 获得FeatureCLass
  5. 通过 SSH 端口转发实现异地内网服务器互通
  6. JS 判断URL中是否含有 http:// 如果没有则自动为URL加上
  7. nginx伪装user-agent等
  8. 【模板】并查集 两种路径压缩写法(类模板和函数模板)
  9. Spring—Quartz定时调度CronTrigger时间配置格式说明与实例
  10. iis负载均衡与文件同步[网摘]