参考:

http://blog.csdn.net/wklken/article/details/7364390

http://hankjin.blog.163.com/blog/static/3373193720105140583594/

1、基本用法:

 res=urllib2.urlopen(url)
print res.read()

2. 加上要get或post的数据

 data={"name":"hank", "passwd":"hjz"}
urllib2.urlopen(url, urllib.urlencode(data))

3. 加上http头

 header={"User-Agent": "Mozilla-Firefox5.0"}
urllib2.urlopen(url, urllib.urlencode(data), header)

4. 加上session

 cj = cookielib.CookieJar()
cjhandler=urllib2.HTTPCookieProcessor(cj)
opener = urllib2.build_opener(cjhandler)
urllib2.install_opener(opener)

5. 加上Basic认证

 password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://www.163.com/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)

6. 使用代理

 proxy_support = urllib2.ProxyHandler({"http":"http://1.2.3.4:3128/"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

7. 设置超时

socket.setdefaulttimeout(5)
或者
urllib2.urlopen(url, timeout=5)

大段代码参考:

     #!/usr/bin/python
# -*- coding:utf-8 -*-
# urllib2_test.py
# author: wklken
# 2012-03-17 wklken@yeah.net import urllib,urllib2,cookielib,socket url = "http://www.testurl....." #change yourself
#最简单方式
def use_urllib2():
try:
f = urllib2.urlopen(url, timeout=5).read()
except urllib2.URLError, e:
print e.reason
print len(f) #使用Request
def get_request():
#可以设置超时
socket.setdefaulttimeout(5)
#可以加入参数 [无参数,使用get,以下这种方式,使用post]
params = {"wd":"a","b":""}
#可以加入请求头信息,以便识别
i_headers = {"User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1) Gecko/20090624 Firefox/3.5",
"Accept": "text/plain"}
#use post,have some params post to server,if not support ,will throw exception
#req = urllib2.Request(url, data=urllib.urlencode(params), headers=i_headers)
req = urllib2.Request(url, headers=i_headers) #创建request后,还可以进行其他添加,若是key重复,后者生效
#request.add_header('Accept','application/json')
#可以指定提交方式
#request.get_method = lambda: 'PUT'
try:
page = urllib2.urlopen(req)
print len(page.read())
#like get
#url_params = urllib.urlencode({"a":"1", "b":"2"})
#final_url = url + "?" + url_params
#print final_url
#data = urllib2.urlopen(final_url).read()
#print "Method:get ", len(data)
except urllib2.HTTPError, e:
print "Error Code:", e.code
except urllib2.URLError, e:
print "Error Reason:", e.reason def use_proxy():
enable_proxy = False
proxy_handler = urllib2.ProxyHandler({"http":"http://proxyurlXXXX.com:8080"})
null_proxy_handler = urllib2.ProxyHandler({})
if enable_proxy:
opener = urllib2.build_opener(proxy_handler, urllib2.HTTPHandler)
else:
opener = urllib2.build_opener(null_proxy_handler, urllib2.HTTPHandler)
#此句设置urllib2的全局opener
urllib2.install_opener(opener)
content = urllib2.urlopen(url).read()
print "proxy len:",len(content) class NoExceptionCookieProcesser(urllib2.HTTPCookieProcessor):
def http_error_403(self, req, fp, code, msg, hdrs):
return fp
def http_error_400(self, req, fp, code, msg, hdrs):
return fp
def http_error_500(self, req, fp, code, msg, hdrs):
return fp def hand_cookie():
cookie = cookielib.CookieJar()
#cookie_handler = urllib2.HTTPCookieProcessor(cookie)
#after add error exception handler
cookie_handler = NoExceptionCookieProcesser(cookie)
opener = urllib2.build_opener(cookie_handler, urllib2.HTTPHandler)
url_login = "https://www.yourwebsite/?login"
params = {"username":"user","password":""}
opener.open(url_login, urllib.urlencode(params))
for item in cookie:
print item.name,item.value
#urllib2.install_opener(opener)
#content = urllib2.urlopen(url).read()
#print len(content)
#得到重定向 N 次以后最后页面URL
def get_request_direct():
import httplib
httplib.HTTPConnection.debuglevel = 1
request = urllib2.Request("http://www.google.com")
request.add_header("Accept", "text/html,*/*")
request.add_header("Connection", "Keep-Alive")
opener = urllib2.build_opener()
f = opener.open(request)
print f.url
print f.headers.dict
print len(f.read()) if __name__ == "__main__":
use_urllib2()
get_request()
get_request_direct()
use_proxy()
hand_cookie()

测试wsgi接口的小例子:

 url ='http://192.168.33.11:9008/getActivityInfo'
data = '''{"userid":"123","type":"1","flag":"t32"}'''
# 使用 urllib.urlencode会报错。。
# response = urllib2.urlopen(url, urllib.urlencode(data))
response = urllib2.urlopen(url, data)
print response.getcode()
print response.read()

python-urllib2模块的更多相关文章

  1. Python urllib2 模块学习笔记

    2015.3.6  urllib2的使用方法大致如下 # 定制Handler处理函数 opener = urllib2.build_opener(ProxyHandler, HTTPHandler) ...

  2. python urllib2模块携带cookie

    今天干活遇到一个事.有一些网站的一些操作非得要求你登陆才能做,比如新浪微博,你要随便看看吧,不行,非得让你登陆了才能看,再比如一些用户操作,像更改自己的资料啦,个人的隐私啦巴拉巴拉的.想抓取这样的ur ...

  3. Python urllib2 模块

    urllib2.urlopen(url, data=None, timeout=<object object>) :用于打开一个URL,URL可以是一个字符串也可以是一个请求对象,data ...

  4. python网页请求urllib2模块简单封装代码

    这篇文章主要分享一个python网页请求模块urllib2模块的简单封装代码. 原文转自:http://www.jbxue.com/article/16585.html 对python网页请求模块ur ...

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

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

  6. Python第十三天 django 1.6 导入模板 定义数据模型 访问数据库 GET和POST方法 SimpleCMDB项目 urllib模块 urllib2模块 httplib模块 django和web服务器整合 wsgi模块 gunicorn模块

    Python第十三天   django 1.6   导入模板   定义数据模型   访问数据库   GET和POST方法    SimpleCMDB项目   urllib模块   urllib2模块 ...

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

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

  8. Python的urllib和urllib2模块

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

  9. urllib2模块中文翻译与学习 - Python 2.7.8官方文档

    总结 目的 打开指定网址 要求 了解需要处理的网站的操作流程 数据包的构造与提交 对可能的响应处理选择合适的处理器(模块内的各种 *Handler()) 核心 urllib.urlencode(que ...

  10. cookielib和urllib2模块相结合模拟网站登录

    1.cookielib模块 cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib2模块配合使用来访问Internet资源.例如可以利用 本模块的CookieJar类的对 ...

随机推荐

  1. 几个MVC属性

    1   用于显示提示字符串 [Required(ErrorMessage="请输入类型名称")] public string ArticleTypeName { get; set; ...

  2. 封装一个ISortable接口

    using System;/// <summary>/// 排序规范/// </summary>/// <typeparam name="T"> ...

  3. NFS文件共享系统

    1.NFS介绍 NFS是Network File System的缩写,主要功能是通过网络让不同的机器系统之间可以彼此共享文件或目录.NFS服务器可以允许NFS客户端将远端NFS服务端的共享目录挂载到本 ...

  4. Angularjs总结(八)$ cookie和$rootscope

    AngularJS 提供了很好的 $cookie 和 $cookieStore API 用来处理 cookies .这两个服务都能够很好的发挥HTML5 cookies,当HTML5 API可用时浏览 ...

  5. 修改sqlplus提示符

    如图所示 : 修改 提示符为 username(sid_serial#)@instance_name ,这样其实很方便的 以下是步骤 在11g中glogin.sql 文件是不存在的,取而代之的是 lo ...

  6. sublime_2014-11-19

    http://xionggang163.blog.163.com/blog/static/376538322013930104310297/ 直接输入注册码就可以了 ----- BEGIN LICEN ...

  7. 【培训】Linux笔记 自学

    1.关机 查看在线用户 who:查看网络联机状态 netstat -a:查看后台执行程序 ps -aux 关机 shutdown -h now.init 0 halt.poweroff 硬件关机 重启 ...

  8. vim 自動化配置

    Vim是Linux系統上常用的編輯器/Text Editor.不過很多人由於不瞭解如何配置,增加了很多煩惱. 今天介紹一個自動化的配置spf13,直接下載製作好的配置並進行自動設置. 1.官方的安裝步 ...

  9. OpenJudge 2749 分解因数

    1.链接地址: http://bailian.openjudge.cn/practice/2749/ 2.题目: 总时间限制: 1000ms 内存限制: 65536kB 描述 给出一个正整数a,要求分 ...

  10. go build 时报错 cc1.exe: sorry, unimplemented: 64-bit mode not compiled in

    最近在玩Go win下尝试编译Go的时候遇到了下面提示(可能是gorocksdb用到了gcc) gcc也需要64位的 最后找到了个帖子: https://github.com/mattn/go-sql ...