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. Python List insert()方法详解

    1.功能insert()函数用于将指定对象插入列表的指定位置. 2.语法list.insert(index, obj) 3.参数index: 对象obj需要插入的索引位置.obj: 插入列表中的对象. ...

  2. acm几何

    fzu 2231,N个点求构成的平行四边行个数. 题意简重点在优化上 #include <cstdio> #include <iostream> #include <cs ...

  3. asp.net使用session完成: 从哪个页面进入登录页面,登录成功还回到那个页面

    1.在Login.aspx页面Load中加入 if (!IsPostBack && Request.UrlReferrer != null) {      Session[ " ...

  4. Django中过期@cache_page中缓存的views数据

    django的缓存系统中,cache_page 这个装饰器非常好用,只要添加一个装饰器就可以缓存views的响应内容,但是django没有提供过期这个views缓存数据的功能. @cache_page ...

  5. Docker: How to enable/disable HTTP Proxy in Toolbox

     1. docker-machine ssh default 2. sudo vi /var/lib/boot2docker/profile 3. # replace with your offi ...

  6. 【完整的App项目】颖火虫笔记v2

    好久没写博客了,一方面是因为最近确实很忙,另一方面自己在改进颖火虫笔记这款App,在前面说过该App主要是模仿的印象笔记,(还不知道的,请看:http://blog.csdn.net/htq__/ar ...

  7. Android线性布局

    线性布局 LinearLayout 是一个视图组,用于使所有子视图在单个方向(垂直或水平)保持对齐. 您可以使用 android:orientation 属性指定布局方向. LinearLayout ...

  8. Dynamics CRM 权限整理二

    接上篇http://blog.csdn.net/vic0228/article/details/50510605,继续列举CRM相关权限 prvReadBusinessUnit privilege(I ...

  9. ListView之侧滑删除

    SwipeMenuListView 是一个为listview添加item侧滑菜单的开源库,项目地址:https://github.com/baoyongzhang/SwipeMenuListView ...

  10. 在非ViewController中显示AlertController的方法

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 以前我们可以在任何类中使用UIAlertView的show实例 ...