一、最简单的使用

import urllib,urllib2

response = urllib2.urlopen("https://www.baidu.com")
print response.read()

二、构造Request对象

request = urllib2.Request("https://www.baidu.com")
response = urllib2.urlopen(request)
print response.read()

三、通过POST 、GET 方式请求

  POST

values = {'username':'test','passwrod':''}
data = urllib.urlencode(values)
print data # username=test&passwrod=123
request = urllib2.Request("https://www.baidu.com",data=data)
response = urllib2.urlopen(request)
print response.read()

  GET

value = {}
value['username']='test'
value['password']=''
data = urllib.urlencode(value)
url = "https://www.baidu.com"+"?"+data
print url # https://www.baidu.com?username=test&password=123
request = urllib2.Request(url=url)
response = urllib2.urlopen(request)
print response.read()

四、quote,进行编码

a = '哈哈'
A = urllib.quote(a)
print A
B = urllib.unquote(A)
print B

  urlencode在 三 中的 GET 部分已有样例

五、设置请求头 header

url = "https://www.baidu.com"
value = {"username":"test","password":""}
data = urllib.urlencode(value)
header = {
"User-Agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0",
"Referer":"http://tieba.baidu.com/f?kw=%E4%BF%9D%E5%AE%9A&ie=utf-8&pn=50"
}
request = urllib2.Request(url=url,data=data,headers=header)
response = urllib2.urlopen(request)
print response.read()

urlopen是urllib2.OpenerDirector的一个实例,一个opener ,一个特殊的默认的opener.因此,这个opener并不能总是满足我们的需求,
这个时候,就需要我们自己构造自己的opener了。

源码摘录

_opener = None
def install_opener(opener):
global _opener
_opener = opener
# ————————————————————————————————————————————————
def urllopen():
"""..."""
return opener.open(url, data, timeout)

六、设置代理

enable_proxy = True
proxy_handler = urllib2.ProxyHandler({"http" : 'http://some-proxy.com:8080'})
null_proxy = urllib2.ProxyHandler({})
if enable_proxy:
opener = urllib2.build_opener(proxy_handler) #创建一个opener对象
else:
opener = urllib2.build_opener(null_proxy)
#
urllib2.install_opener(opener) #全局应用该opener request = urllib2.Request("https://www.baidu.com")
response = opener.open(request)
response = urllib2.urlopen(request)
#
print response.read()

七、操作cookie

import cookielib

#创建一个CookieJar实例来保存cookie
cookie = cookielib.CookieJar() # 创建 Cookie 处理器
handler = urllib2.HTTPCookieProcessor(cookie) #创建一个 opener
opener = urllib2.build_opener(handler) # 用带有cookie 处理器的opener 来请求url
response = opener.open("https://www.baidu.com")
#
for item in cookie:
print item #<Cookie BIDUPSID=25441729620BF793C1BE08CA0B43C8D4 for .baidu.com/>
print 'Name = '+item.name #Name = BIDUPSID
print 'Value = '+item.value #Value = 25441729620BF793C1BE08CA0B43C8D4

八、保存cookie到文件

import cookielib

filename = "/home/an/savecookie.test"
#创建一个 MozillaCookieJar 对象来保存cookie ,稍后写入对象
cookie = cookielib.MozillaCookieJar(filename)
# 创建 cookie 处理器
handle = urllib2.HTTPCookieProcessor(cookie)
#构建 handler
opener = urllib2.build_opener(handle) response = opener.open("http://www.baidu.com")
#保存cookie到文件
cookie.save(ignore_discard=True,ignore_expires=True)
# ignore_discard 即使cookie被丢弃也保存下来。
# ignore_expires 如果该文件中的cookie已存在,那么就覆盖

九、从文件中取出cookie并使用

import cookielib

cookie = cookielib.MozillaCookieJar()
cookie.load("/home/an/savecookie.test",ignore_expires=True,ignore_discard=True) handler = urllib2.HTTPCookieProcessor(cookie)
opener = urllib2.build_opener(handler) request = urllib2.Request("http://www.baidu.com")
response = opener.open(request)
print response.read()

urllib 和urllib2 模块使用简例的更多相关文章

  1. Python的urllib和urllib2模块

    Python的urllib和urllib2模块都做与请求URL相关的操作,但他们提供不同的功能.他们两个最显着的差异如下: urllib2可以接受一个Request对象,并以此可以来设置一个URL的h ...

  2. Python urllib和urllib2模块学习(二)

    一.urllib其它函数 前面介绍了 urllib 模块,以及它常用的 urlopen() 和 urlretrieve()函数的使用介绍.当然 urllib 还有一些其它很有用的辅助方法,比如对 ur ...

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

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

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

    build_opener()详解: 1.urllib2.urlopen()函数不支持验证.cookie或者其它HTTP高级功能,要支持这些功能,必须使用build_opener()函数创建自定这句话的 ...

  5. 深入理解urllib、urllib2及requests

    urllib and urllib2 区别 –博主提示:下面的是python2中的用法,python3需要做出相应修改. urllib和urllib2模块都做与请求URL相关的操作,但他们提供不同的功 ...

  6. 理解urllib、urllib2及requests区别及运用

    urllib and urllib2 区别 –博主提示:下面的是python2中的用法,python3需要做出相应修改. urllib和urllib2模块都做与请求URL相关的操作,但他们提供不同的功 ...

  7. urllib与urllib2的学习总结

    先啰嗦一句,我使用的版本是python2.7,没有使用3.X的原因是我觉得2.7的扩展比较多,且较之前的版本变化不大,使用顺手.3.X简直就是革命性的变化,用的蹩手.3.x的版本urllib与urll ...

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

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

  9. 关于urllib、urllib2爬虫伪装的总结

    站在网站管理的角度,如果在同一时间段,大家全部利用爬虫程序对自己的网站进行爬取操作,那么这网站服务器能不能承受这种负荷?肯定不能啊,如果严重超负荷则会时服务器宕机(死机)的,对于一些商业型的网站,宕机 ...

随机推荐

  1. 如何使用button在tab中新建打开一个链接页

    在APPBOX某页中如何使用button按钮打开一个新的链接页.比如说百度.谷歌等 在后台的单击事件中使用以下语句即            string url = "DownloadIma ...

  2. 最新hadoop入门教程汇总篇(附详细图文步骤)

    关于hadoop的分享此前一直都是零零散散的想到什么就写什么,整体写的比较乱吧.最近可能还算好的吧,毕竟花了两周的时间详细的写完的了hadoop从规划到环境安装配置等全部内容.写过程不是很难,最烦的可 ...

  3. python findall() re.S

    官方文档:https://docs.python.org/3.6/library/re.html 教程:http://www.regexlab.com/zh/regref.htm re.findall ...

  4. 服务注册发现Eureka之一:Spring Cloud Eureka的服务注册与发现

    Spring Cloud简介 Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为基于JVM的云应用开发中的配置管理.服务发现.断路器.智能路由.微代理.控制总线.全局锁 ...

  5. Program.cs 累积_C#

    using System; using System.Diagnostics; using System.Threading; using System.Windows.Forms; using Ut ...

  6. js之ActiveX控件使用说明 new ActiveXObject()

    什么是 ActiveX 控件? ActiveX 控件广泛用于 Internet.它们可以通过提供视频.动画内容等来增加浏览的乐趣.不过,这些程序可能出问题或者向您提供不需要的内容.在某些情况下,这些程 ...

  7. 032:基于Consul和MGR的MySQL高可用架构

    目录 一.Consul 1.Consul简介 2.准备环境 3.Consul 安装 4.Consul配置文件 5.Consul 服务检查脚本 6.Consul启动 二.MGR搭建 1.MGR配置 2. ...

  8. Logistic回归的两种形式y=0/1,y=+1/-1

    第一种形式:y=0/1 第二种形式:y=+1/-1 第一种形式的损失函数可由极大似然估计推出: 第二种形式的损失函数:  , 参考:https://en.wikipedia.org/wiki/Loss ...

  9. 【Linux_Unix系统编程】Chapter8 用户和组

    chapter8 用户和组 8.1 密码文件 /etc/passwd 每行都包含7个字段,之间用冒号分割,如下所示: mtk:x:1000:100:Michael:/home/mtk:/bin/bas ...

  10. Python print函数参数详解

    官方文档 print(…)    print(value, …, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)    Prints the valu ...