python中urllib2.request post如何post request payload?

2774人阅读
1、使用python的库urllib2,用到urlopen和Request方法。
2、方法urlopen原形
urllib2.urlopen(url[,
data][, timeout])
url表示目标网页地址,可以是字符串,也可以是请求对象Request
data表示post方式提交给目标服务器的参数
timeout表示超时时间设置
改方法返回一个类似文件的对象,有geturl()、info()、read()方法其中geturl()返回连接地址,info()返回网页信息。
要获取网页内容可以使用read()方法,read也可以带参数,表示读取内容的大小(字节)。
&&& import urllib2
&&& socket = urllib2.urlopen(&&)
&&& content = socket.read()
&&& socket.close()
这样,网页的内容(content)就爬下来了,但是有些网站禁止爬虫,如果直接请求会出现以下错误:
urllib2.HTTPError: HTTP Error 403: Forbidden
解决方法是可以在请求加上头信息,伪装成浏览器的访问行为,需要用到Request方法:
3、方法Request原型
urllib2.Request(url[,
data][, headers][, origin_req_host][, unverifiable])
url表示目标网页地址,可以是字符串,也可以是请求对象Request
data表示post方式提交给目标服务器的参数
headers表示用户标识,是一个字典类型的数据,有些不允许脚本的抓取,所以需要用户代理,像火狐浏览器的代理就是类似:Mozilla/5.0 (X11; U; Linux i686)Gecko/ Firefox/2.0.0.11 浏览器的标准UA格式为:浏览器标识 (操作系统标识; 加密等级标识; 浏览器语言) 渲染引擎标识 版本信息 ,headers默认是Python-urllib/2.6
origin_req_host表示请求方的主机域名或者ip地址
unverifiable还没搞懂。。。
看一个例子:
&&& headers = {'User-Agent':'Mozilla/5.0 (X11; U; Linux i686)Gecko/ Firefox/2.0.0.11'}
&&& req = urllib2.Request(url=&http://blog.csdn.net/deqingguo&,headers=headers)
&&& socket = urllib2.urlopen(req)
&&& content = socket.read()
&&& socket.close()
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:49864次
排名:千里之外
原创:41篇
转载:10篇
(2)(1)(1)(1)(2)(1)(3)(1)(5)(2)(3)(8)(21)1675人阅读
python urllib2技术补充参考--中文版01
python urllib2技术补充参考--中文版01
此文由我()翻译自。原文标题:urllib2
- The Missing Manual -副标题:HOWTO Fetch Internet Resources with Python。英文版权归文章原作者所有。转载请保留以上信息。
行文仓促,未作校正,请谅解指正。
-----------------------------------------------------------我是分割线---------------------------------------------------------
urllib2是python的一个获取url(Uniform Resource Locators,统一资源定址器)的模块。它用urlopen函数的形式提供了一个非常简洁的接口。这使得用各种各样的协议获取url成为可能。它同时 也提供了一个稍微复杂的接口来处理常见的状况-如基本的认证,cookies,代理,等等。这些都是由叫做opener和handler的对象来处理的。
urlib2支持获取url的多种url 协议(以url中“:”前的字符串区别,如ftp是ftp形式的url 协议),用它们关联的网络协议(如HTTP,FTP)。这个教程著重于最普遍的情况--HTTP。
最简单的情况下urlopen用起来非常简单。但随着你打开HTTP ur时遇到错误或无意义的事情,你需要对HTTP的一些理解。对HTTP最权威最容易让人理解的参考是。这是一个技术文档,而且不太容易读懂。这篇HOWTO意在用足够关于HTTP的细节阐明urllib2,使你明白。它的意图不在替换,而是对它们的一个补充。
以下是获取url最简单的方式:
importurllib2
response =
urllib2.urlopen('http://python.org/')
response.read()
许多urlib2的使用都是如此简单(注意我们本来也可以用一个以“ftp:”“file:”等开头的url取代“HTTP”开头的url).然而,这篇教程的目的是解释关于HTTP更复杂的情形。
HTTP建基于请求和回应(requests &responses )-客户端制造请求服务器返回回应。urlib2用代 表了你正在请求的HTTP request的Request对象反映了这些。用它最简单的形式,你建立了一个Request对象来明确指明你想要获取的url。调用urlopen函 数对请求的url返回一个respons对象。这个respons是一个像file的对象,这意味着你能用.read()函数操作这个respon对象:
importurllib2
urllib2.Request('http://www.voidspace.org.uk')
response =
urllib2.urlopen(req)
the_page =
response.read()
注意urlib2利用了同样的Request接口来处理所有的url协议。例如,你可以像这样请求一个ftpRequest:
urllib2.Request('/')
对于HTTP,Request对象允许你做两件额外的事:第一,你可以向服务器发送数据。第二,你可以向服务器发送额外的信息(metadata),这些信息可以是关于数据本身的,或者是关于这个请求本身的--这些信息被当作HTTP头发送。让我们依次看一下这些。
有时你想向一个URL发送数据(通常这些数据是代表一些CGI脚本或者其他的web应用)。对于HTTP,这通常叫做一个Post。当你发送一个你 在网上填的form(表单)时,这通常是你的浏览器所做的。并不是所有的Post请求都来自HTML表单,这些数据需要被以标准的方式encode,然后 作为一个数据参数传送给Request对象。Encoding是在urlib中完成的,而不是在urlib2中完成的。
import urllib2
'/cgi-bin/register.cgi'
'Michael Foord',
&&&&&&&&&&'location' :'Northampton',
&&&&&&&&&&'language' :'Python'
urllib.urlencode(values)
urllib2.Request(url,data)
response =
urllib2.urlopen(req)
the_page =
response.read()
注意有时需要其他的Encoding(例如,对于一个来自表单的文件上传(file upload)--详细内容见
如果你不传送数据参数,urlib2使用了一个GET请求。一个GET请求和POST请求的不同之处在于POST请求通常具有边界效应:它们以某种 方式改变系统的状态。(例如,通过网页设置一条指令运送一英担罐装牛肉到你家。)虽然HTTP标准清楚的说明Post经常产生边界效应,而get从不产生 边界效应,但没有什么能阻止一个get请求产生边界效应,或一个Post请求没有任何边界效应。数据也能被url自己加密(Encoding)然后通过一 个get请求发送出去。
这通过以下实现:
&&& import urllib2
&&& import urllib
&&& data = {}
&&& data['name'] = 'Somebody Here'
&&& data['location'] = 'Northampton'
&&& data['language'] = 'Python'
&&& url_values = urllib.urlencode(data)
&&& print url_values
name=Somebody+Here&language=Python&location=Northampton
&&& url = '/example.cgi'
&&& full_url = url + '?' + url_values
&&& data = urllib2.open(full_url)
注意一个完整的url通过加入 ?产生,?之后跟着的是加密的数据。
我们将会在这里讨论一个特殊的HTTP头,来阐释怎么向你的HTTP请求中加入头。
有一些网站不希望被某些程序浏览或者针对不同的浏览器返回不同的版本。默认情况下,urlib2把自己识别为Python-urllib/x.y(这里的xy是python发行版的主要或次要的版本号,如,Python-urllib/2.5),这些也许会混淆站点,或者完全不工作。浏览器区别自身的方式是通过User-Agent头。当你建立一个Request对象时,你可以加入一个头字典。接下来的这个例子和上面的请求一样,不过它把自己定义为IE的一个版本。
import urllib2
'/cgi-bin/register.cgi'
user_agent =
'Mozilla/4.0 ( MSIE 5.5; Windows NT)'
'Michael Foord',
&&&&&&&&&&'location' :'Northampton',
&&&&&&&&&&'language' :'Python'
{ 'User-Agent' :user_agent
urllib.urlencode(values)
urllib2.Request(url,data,
response =
urllib2.urlopen(req)
the_page =
response.read()
Respons同样有两种有用的方法。当我们出差错之后,看一下关于info and geturl的部分。
异常处理:
不能处理一个respons时,urlopen抛出一个urlerror(虽然像平常一样对于python APIs,内建异常如,ValueError, TypeError 等也会被抛出。)
HTTPerror是HTTP URL在特别的情况下被抛出的URLError的一个子类。
urlerror:
通常,urlerror被抛出是因为没有网络连接(没有至特定服务器的连接)或者特定的服务器不存在。在这种情况下,含有reason属性的异常将被抛出,以一种包含错误代码和文本错误信息的tuple形式。
&&& req = urllib2.Request('http://www.pretend_server.org')
&&& try: urllib2.urlopen(req)
&&& except URLError, e:
print e.reason
(4, 'getaddrinfo failed')
HTTPError:
每个来自服务器的HTTP response包含一个“status code”(状态代码)。有时状态代码暗示了服务器不能处理这个请求。默认的句柄将会为你处理一些response(如,如果返回的是一个要求你从一个不同的url获取文件的“重定向”,urlib2将会为你处理)。对于那些它不能处理的,urlopen将会抛出一个HTTPerror。
典型的错误包含404(页面没有找到),403(请求禁止)和401(需要许可)。
所有的HTTP错误代码参见RFC2616的第十部分。
HTTP错误代码将会有一个code(integer)属性,这个code属性的integer值和服务器返回的错误代码是一致的。
错误代码:
因为默认的句柄处理重定向(300序列中的代码)和在100-299之间表示成功的代码,你通常只需要了解在400-599序列中的错误代码。
BaseHTTPServer.BaseHTTPRequestHandler.responses是一个有用的response字典,其中的代码显示了所有RFC2616使用的response代码。
为了方便,代码被复制到了这里:
responses = {
&&&&100: ('Continue', 'Request received, please continue'),
&&&&101: ('Switching Protocols',
&&&&&&&&&&'Switc obey Upgrade header'),
&&&&200: ('OK', 'Request fulfilled, document follows'),
&&&&201: ('Created', 'Document created, URL follows'),
&&&&202: ('Accepted',
&&&&&&&&&&'Request accepted, processing continues off-line'),
&&&&203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
&&&&204: ('No Content', 'Request fulfilled, nothing follows'),
&&&&205: ('Reset Content', 'Clear input form for further input.'),
&&&&206: ('Partial Content', 'Partial content follows.'),
&&&&300: ('Multiple Choices',
&&&&&&&&&&'Object has several resources -- see URI list'),
&&&&301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
&&&&302: ('Found', 'Object moved temporarily -- see URI list'),
&&&&303: ('See Other', 'Object moved -- see Method and URL list'),
&&&&304: ('Not Modified',
&&&&&&&&&&'Document has not changed since given time'),
&&&&305: ('Use Proxy',
&&&&&&&&&&'You must use proxy specified in Location to access this '
&&&&&&&&&&'resource.'),
&&&&307: ('Temporary Redirect',
&&&&&&&&&&'Object moved temporarily -- see URI list'),
&&&&400: ('Bad Request',
&&&&&&&&&&'Bad request syntax or unsupported method'),
&&&&401: ('Unauthorized',
&&&&&&&&&&'No permission -- see authorization schemes'),
&&&&402: ('Payment Required',
&&&&&&&&&&'No payment -- see charging schemes'),
&&&&403: ('Forbidden',
&&&&&&&&&&'Request forbidden -- authorization will not help'),
&&&&404: ('Not Found', 'Nothing matches the given URI'),
&&&&405: ('Method Not Allowed',
&&&&&&&&&&'Specified method is invalid for this server.'),
&&&&406: ('Not Acceptable', 'URI not available in preferred format.'),
&&&&407: ('Proxy Authentication Required', 'You must authenticate with '
&&&&&&&&&&'this proxy before proceeding.'),
&&&&408: ('Request Timeout', 'R try again later.'),
&&&&409: ('Conflict', 'Request conflict.'),
&&&&410: ('Gone',
&&&&&&&&&&'URI no longer exists and has been permanently removed.'),
&&&&411: ('Length Required', 'Client must specify Content-Length.'),
&&&&412: ('Precondition Failed', 'Precondition in headers is false.'),
&&&&413: ('Request Entity Too Large', 'Entity is too large.'),
&&&&414: ('Request-URI Too Long', 'URI is too long.'),
&&&&415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
&&&&416: ('Requested Range Not Satisfiable',
&&&&&&&&&&'Cannot satisfy request range.'),
&&&&417: ('Expectation Failed',
&&&&&&&&&&'Expect condition could not be satisfied.'),
&&&&500: ('Internal Server Error', 'Server got itself in trouble'),
&&&&501: ('Not Implemented',
&&&&&&&&&&'Server does not support this operation'),
&&&&502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
&&&&503: ('Service Unavailable',
&&&&&&&&&&'The server cannot process the request due to a high load'),
&&&&504: ('Gateway Timeout',
&&&&&&&&&&'The gateway server did not receive a timely response'),
&&&&505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
当一个错误被抛出的时候,服务器返回一个HTTP错误代码和一个错误页。你可以使用返回的HTTP错误示例。这意味着它不但具有code属性,而且同时
具有read,geturl,和info,methods属性。
&&& req = urllib2.Request('http://www.python.org/fish.html')
urllib2.urlopen(req)
&&& except URLError, e:
print e.code
print e.read()
&!DOCTYPE html PUBLIC &-//W3C//DTD HTML 4.01 Transitional//EN&
&http://www.w3.org/TR/html4/loose.dtd&&
&?xml-stylesheet href=&./css/ht2html.css&
type=&text/css&?&
&html&&head&&title&Error 404: File Not Found&/title&
...... etc
--------------------------------------------------------------我是分割线----------------------------------------------------------
&&python urllib2技术补充参考--中文版02python
urllib2技术补充参考--中文版02此文由我()翻译自。原文标题:urllib2
- The Missing Manual -副标题:HOWTO Fetch Internet Resources with Python。英文版权归文章原作者所有。转载请保留以上信息。行文仓促,未作校正,请谅解指正。-----------------------------------------------------------我是分割线-----------------------------------------------------容错:
如果你准备处理HTTP错误和URL错误这里有两种基本的方法,我更倾向于后一种: 1 from urllib2 import Request, urlopen, URLError, HTTPError req = Request(someurl) try: &&& response = urlopen(req) except HTTPError, e: &&& print 'The server couldn\'t fulfill the request.'
&&& print 'Error code: ', e.code except URLError, e: &&& print 'We failed to reach a server.' &&& print 'Reason: ', e.reason else: &&& # everything is fine 注意HTTP错误异常必须在前面,否则URL错误也会捕获一个HTTP错误。 2 from urllib2 import Request,
urlopen, URLError req = Request(someurl) try: &&& response = urlopen(req) except URLError, e: &&& if hasattr(e, 'reason'): &&&&&&& print 'We failed to reach a server.' &&&&&&& print 'Reason: ', e.reason &&& elif hasattr(e, 'code'): &&&&&&& print 'The server
couldn\'t fulfill the request.' &&&&&&& print 'Error code: ', e.code else: &&& # everything is fine 注意: URL错误是IO错误异常的一个子类。这意味着你能避免引入(import)URL错误而使用: from urllib2 import Request, urlopen req = Request(someurl) try: &&& response
= urlopen(req) except IOError, e: &&& if hasattr(e, 'reason'): &&&&&&& print 'We failed to reach a server.' &&&&&&& print 'Reason: ', e.reason &&& elif hasattr(e, 'code'): &&&&&&& print 'The server couldn\'t fulfill the request.' &&&&&&& print 'Error code:
', e.code else: &&& # everything is fine 极少数环境下,urllib2能够抛出socket.error. INFO and GETURL urlopen返回的response(或者HTTP错误实例)有两个有用的方法:info和geturl。 geturl--它返回被获取网页的真正的url。这是很有用的,因为urlopen(或使用的opener对象)也许会伴随一个重定向。获取的网页url也许和要求的网页url不一样。
info--它返回一个像字典的对象来描述获取的网页,尤其是服务器发送的头。它现在一般是httplib.HTTPMessage的一个实例。典型的头包含'Content-length', 'Content-type', 等等。看一下Quick Reference to HTTP Headers中,HTTP头列表,还有关于他们简单的解释和使用方法。 Openers 和Handlers 当你获取一个URL时,你使用一个opener(一个可能以一个比较迷糊名字命名的实例--urllib2.OpenerDirector)。正常情况下我们一直使用默认的opener,通过urlopen,但你也可以创建自定义的openers。opener使用操作器(handlers)。所有的重活都交给这些handlers来做。每一个handler知道怎么打开url以一种独特的url协议(http,ftp等等),或者怎么处理打开url的某些方面,如,HTTP重定向,或者HTTP
cookie。 你将会创建openers如果你想要用安装特别的handlers获取url,例如,获取一个处理cookie的opener,或者一个不处理重定向的opener。 枚举一个OpenerDirector,然后多次调用.add_handler(some_handler_instance)来创建一个opener。或者,你可以用build_opener,这是一个很方便的创建opener对象的函数,它只有一个函数调用。build_opener默认会加入许多 handlers,但是提供了一个快速的方法添加更多东西和/或使默认的handler失效。其他你想要的handlers能够处理代理,authentication和其他平常但是又有些特殊的情况。
install_opener能被用于创建一个opener对象,(全局)默认的opener。这意味着调用urlopen将会用到你刚安装的opener。 opener对象有一个open方法,它可以被直接调用来获取url以一种和urlopen函数同样的方式:没有必要调用install_opener,除非是为了方便。 Basic Authentication:(基本验证) 为了解释创建和安装一个handler,我们将会使用
HTTPBasicAuthHandler。更多关于这个东西的内容和详细讨论---包括一个 Basic Authentication如何工作的解说--参见 Basic Authentication Tutorial. 当需要Authentication的时候,服务器发送一个头(同时还有401代码)请求Authentication。它详细指明了一个Authentication和一个域。这个头看起来像: Www-authenticate: SCHEME realm=&REALM&.
e.g. Www-authenticate: Basic realm=&cPanel Users& 客户端然后就会用包含在头中的正确的帐户和密码重新请求这个域。这是“基本验证”。为了简化这个过程,我们可以创建一个 HTTPBasicAuthHandler和opener的实例来使用这个handler。 HTTPBasicAuthHandler用一个叫做密码管理的对象来处理url和用户名和密码的域的映射。如果你知道域是什么(从服务器发送的authentication 头中),那你就可以使用一个HTTPPasswordMgr。多数情况下人们不在乎域是什么。那样使用HTTPPasswordMgrWithDefaultRealm就很方便。它允许你为一个url具体指定用户名和密码。这将会在你没有为一个特殊的域提供一个可供选择的密码锁时提供给你。我们通过提供None作为add_password方法域的参数指出这一点。最高级别的url是需要authentication的第一个url。比你传递给.add_password()的url更深的url同样也会匹配。 #
create a password manager password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm() # Add the username and password. # If we knew the realm, we could use it instead of ``None``. top_level_url = &/foo/& password_mgr.add_password(None, top_level_url,
username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr) # create &opener& (OpenerDirector instance) opener = urllib2.build_opener(handler) # use the opener to fetch a URL opener.open(a_url) # Install the opener. # Now all calls to urllib2.urlopen
use our opener. urllib2.install_opener(opener) 注意在以上的示例中我们只给build_opener提供了HTTPBasicAuthHandler。默认opener有对普通情况的操作器(handlers)- ProxyHandler, UnknownHandler, HTTPHandler, HTTPDefaultErrorHandler, HTTPRedirectHandler, FTPHandler, FileHandler, HTTPErrorProcessor.
高级别url实际上是一个完整的url(包括http:协议组件和主机名可选的端口号),如“”或者是一个授权(同样,主机名,可选的端口号)如“&& 或 &:8080”(后一个示例包含了一个端口号)。授权,如果被呈现,一定不能包含用户信息-如“oe@” 是不正确的、 代理: urllib2将会自动检测你的代理设置并使用它们。这是通过
ProxyHandler实现的,它是操作器链的一部分。正常情况下,这是个好东西,但是也有它不那么有用的偶然情况。一个做这些的方法是安装我们自己的ProxyHandler,不用任何定义任何代理。使用一个和建立Basic Authentication操作器相似的步骤可以实现: &&& proxy_support = urllib2.ProxyHandler({}) &&& opener = urllib2.build_opener(proxy_support)
&&& urllib2.install_opener(opener) 注意:目前urllib2不支持通过代理获取HTTPs位置。这是一个问题。 sockets和layers python支持获取层叠的网页的源码。urllib2使用httplib library,而httplib library反过来使用socket library。对于python2.3你可以指明一个socket应该在超时之前等待response多久。这在这些不得不获取网页的应用中很有用。默认socket模块没有超时而且能够挂起。目前,socket超时在urllib2或者httplib水平中不可见。然而,你可以全局地为所有socket设置默认的超时。 import
socket import urllib2 # timeout in seconds timeout = 10 socket.setdefaulttimeout(timeout) # this call to urllib2.urlopen now uses the default timeout # we have set in the socket module req = urllib2.Request('http://www.voidspace.org.uk') response = urllib2.urlopen(req)
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:41575次
排名:千里之外
转载:17篇
(3)(1)(1)(2)(7)(5)(5)页面导航:
→ 正文内容 Python模仿POST提交HTTP数据及使用Cookie值
Python模仿POST提交HTTP数据及使用Cookie值的方法
这篇文章主要介绍了Python模仿POST提交HTTP数据及使用Cookie值的方法,通过两种不同的实现方法较为详细的讲述了HTTP数据通信及cookie的具体用法,需要的朋友可以参考下
本文实例讲述了在Python中模仿POST HTTP数据及带Cookie提交数据的实现方法,分享给大家供大家参考。具体实现方法如下:
如果不使用Cookie, 发送HTTP POST非常简单:
代码如下:import urllib2, urllib
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
&&&&&&& url&&&& = 'http://www.jb51.net/',
&&&&&&& data&&& = urllib.urlencode(data)
print f.read()
当使用Cookie时, 代码变得有些复杂:
代码如下:import urllib2
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
f = opener.open('http://www.xxxx.net/?act=login&name=user01')
data = '&root&Hello&/root&'
request = urllib2.Request(
&&&&&&& url&&&& = 'http://www.xxxx.net/?act=send',
&&&&&&& headers = {'Content-Type' : 'text/xml'},
&&&&&&& data&&& = data)
opener.open(request)
第一次 open() 是进行登录. 服务器返回的 Cookie 被自动保存在 cookies 中, 被用在后来的请求.
第二次 open() 用 POST 方法向服务器发送了 Content-Type=text/xml 的数据. 如果你不创建一个 Request, 而是直接使用 urlopen() 方法, Python 强制把 Content-Type 改为 application/x-www-form-urlencoded.
用urllib2库,带Cookie请求URL页面
代码如下:import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("/")
代码如下:import urllib2
import urllib
from cookielib import CookieJar
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
# input-type values from the html form
formdata = { "username" : username, "password": password, "form-id" : "1234" }
data_encoded = urllib.urlencode(formdata)
response = opener.open("/login.php", data_encoded)
content = response.read()
希望本文所述对大家的Python程序设计有所帮助。
您可能感兴趣的文章:
上一篇:下一篇:
最 近 更 新
热 点 排 行
12345678910}

我要回帖

更多关于 python urllib2 https 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信