urllib2.urlopen()

urlib2是使用各种协议完成打开url的一个扩展包。最简单的使用方式是调用urlopen方法,比如
def urlopen(url, data=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
和urllib中不同的是第三个参数为timeout了,所以代理只能在外面设置了。
import urllib2
content_stream = urllib2.urlopen('http://www.baidu.com/')
content = content_stream.read()
print content
而
request = urllib2.Request( url = 'http://www.ideawu.net/?act=send', headers = {'Content-Type' : 'text/xml'}, data = data)
 
 
#!/usr/bin/python
#-*-coding:utf-8-*-
  
import httplib,urllib; #加载模块
 
#定义需要进行发送的数据
params = urllib.urlencode({'title':'标题','content':'文章'});
#定义一些文件头
headers = {"Content-Type":"application/x-www-form-urlencoded",
"Connection":"Keep-Alive","Referer":"http://mod.qlj.sh.cn/sing/post.php"};
#与网站构建一个连接
conn = httplib.HTTPConnection("http://mod.qlj.sh.cn/sing/");
#开始进行数据提交 同时也可以使用get进行
conn.request(method="POST",url="post.php",body=params,headers=headers);
#返回处理后的数据
response = conn.getresponse();
#判断是否提交成功
if response.status == 302:
print "发布成功!";
else:
print "发布失败";
#关闭连接
conn.close();<span id="more-998"></span>

不使用COOKIES 简单提交

import urllib2, urllib
&nbsp;
data = {'name' : 'www', 'password' : '123456'}
f = urllib2.urlopen(
url = 'http://www.ideawu.net/',
data = urllib.urlencode(data)
)
print f.read()#读取全部返回内容
 
print f.info() #取响应header头所有信息
假设信息如下。
Date: Wed, 26 Aug 2009 08:46:03 GMT
Server: Apache/2.2.9 (Unix) PHP/5.2.6
X-Powered-By: PHP/5.2.6
X-Pingback: http://www.ideawu.net/index.php/XXXX
Content-Type: text/html
Connection: closeContent-Length: 31206
那么,如果只取header某一部分信息,如'Content-Type'部分,用:
print f.info().getheader('Content-Type')
 

使用COOKIES 复杂

import urllib2&nbsp;
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)
&nbsp;
f = opener.open('http://www.ideawu.net/?act=login&name=user01')
&nbsp;
data = '<root>Hello</root>'
request = urllib2.Request(
url = 'http://www.ideawu.net/?act=send',
headers = {'Content-Type' : 'text/xml'},
data = data)
&nbsp;
opener.open(request)
 
 
 
一个小例子:

一、打开一个网页获取所有的内容

from urllib import urlopen
doc = urlopen("http://www.baidu.com").read()
print doc
二、获取Http头 from urllib import urlopen
doc = urlopen("http://www.baidu.com")
print doc.info()
print doc.info().getheader('Content-Type')
 三、使用代理 1. 查看环境变量 print ""n".join(["%s=%s" % (k, v) for k, v in os.environ.items()])
print os.getenv("http_proxy")
    2. 设置环境变量 import   os
os.putenv("http_proxy",   "http://proxyaddr:<port>")
     3. 使用代理 # Use http://www.someproxy.com:3128 for http proxying
proxies = {'http': 'http://www.someproxy.com:3128'}
filehandle = urllib.urlopen(some_url, proxies=proxies)
# Don't use any proxies
filehandle = urllib.urlopen(some_url, proxies={})
# Use proxies from environment - both versions are equivalent
filehandle = urllib.urlopen(some_url, proxies=None)
filehandle = urllib.urlopen(some_url) 详细出处参考:http://www.jb51.net/article/15720.htm
 
 

python发送post请求的更多相关文章

  1. python发送post请求上传文件,无法解析上传的文件

    前言 近日,在做接口测试时遇到一个奇葩的问题. 使用post请求直接通过接口上传文件,无法识别文件. 遇到的问题 以下是抓包得到的信息: 以上请求是通过Postman直接发送请求的. 在这里可以看到消 ...

  2. Python发送http请求时遇到问题总结

    1.报错信息为“ERROR 'str' object has no attribute 'endwith'”,排查发现endswith方法名写错了,少了s,写成了 'endwith' if inter ...

  3. python发送网络请求

    1.使用urllib模块(使用不方便,建议使用第二种) get请求: res = urlopen(url) from urllib.request import urlopen url = 'http ...

  4. python发送requests请求时,使用登录的token值,作为下一个接口的请求头信息

    背景介绍: 发送搜索请求时,需要用到登录接口返回值中的token值 代码实现: 登录代码: 搜索接口:

  5. requests模块--python发送http请求

    requests模块 在Python内置模块(urllib.urllib2.httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的 ...

  6. python 发送POST请求

    #博客地址:https://blog.csdn.net/qq_36374896 import urllib.request import urllib.parse url = "http:/ ...

  7. 转载:python发送HTTP请求

    1. [代码]GET 方法 import httplib #----------------------------- conn = httplib.HTTPConnection("www. ...

  8. python 发送GET请求

    # #博客地址:https://blog.csdn.net/qq_36374896 # 特点:把数据拼接到请求路径的后面传递给服务器 # # 优点:速度快 # # 缺点:承载的数据量小,不安全 imp ...

  9. python接口自动化(八)--发送post请求的接口(详解)

    简介 上篇介绍完发送get请求的接口,大家必然联想到发送post请求的接口也不会太难,被聪明的你又猜到了.答案是对的,虽然发送post请求的参考例子很简单,但是实际遇到的情况却是很复杂的,因为所有系统 ...

随机推荐

  1. CMCC验证绕过POC

    大学的时候无意间发现绕过CMCC验证的方法(贫穷使人进步...),写了段POC脚本,时过两年,漏洞应该已经失效了(我猜 --),刚刚发现有人私信问我要,都那么久了鬼还记得写的什么啊,但确实看到了又不能 ...

  2. Radio Station

    B. Radio Station time limit per test:  2 seconds memory limit per test:  256 megabytes input: standa ...

  3. Rails多路径调用相同方法原路返回的方法

    有时候可能有多条path到达同一个method,此时,我们希望在该方法完成后自动转到之前进入的path中去,其实实现起来非常简单,只需要实现如下两个方法: def redirect_back_or(d ...

  4. vue以及js的一些坑或常用技巧

    判断空object Object.getOwnPropertyNames(obj).length === 0 模拟range Array.apply(null, Array(5)).map(funct ...

  5. Spring中配置DataSource的六种方式

    第一种:beans.xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource ...

  6. Spring Security 基础登录实例

    1 新建Java Web项目 导入Jar: 2 修改web.xml <?xml version="1.0" encoding="UTF-8"?> & ...

  7. (译)快速指南:用UIViewPropertyAnimator做动画

    翻译自:QUICK GUIDE: ANIMATIONS WITH UIVIEWPROPERTYANIMATOR 译者:Haley_Wong iOS 10 带来了一大票有意思的新特性,像 UIViewP ...

  8. iOS中的NSURLProtocol

    转自:iOS知识小集 NSURLProtocol类(注意,这个不是协议)经常用于实现一些URL Loading System相关的黑魔法.它可以拦截URL Loading System相关的网络请求, ...

  9. NLP系列(1)_从破译外星人文字浅谈自然语言处理基础

    作者:龙心尘 &&寒小阳 时间:2016年1月. 出处: http://blog.csdn.net/longxinchen_ml/article/details/50543337 ht ...

  10. Android支付——支付宝支付总结

    摘要:分享牛系列.分享牛转载.第三方支付,java第三方支付.android第三方支付. 原文地址:http://blog.csdn.net/zwl5670/article/details/51219 ...