python post

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

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 
cookies = urllib2.HTTPCookieProcessor()
opener = urllib2.build_opener(cookies)

f = opener.open('http://www.ideawu.net/?act=login&name=user01')

data = '<root>Hello</root>'
request = urllib2.Request(
        url     = 'http://www.ideawu.net/?act=send',
        headers = {'Content-Type' : 'text/xml'},
        data    = data)

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

urllib2 post

# -*- coding: cp936 -*-
import urllib2
import urllib
def postHttp(name=None,tel=None,address=None,
       price=None,num=None,paytype=None,
       posttype=None,other=None):
  url="http://www.xxx.com/dog.php"
  #定义要提交的数据
  postdata=dict(name=name,tel=tel,address=address,price=price,
         num=num,paytype=paytype,posttype=posttype,other=other)
  #url编码
  postdata=urllib.urlencode(postdata)
  #enable cookie
  request = urllib2.Request(url,postdata)
  response=urllib2.urlopen(request)
  print response

urllib

import httplib, urllib  
params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})  
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}  
try:  
   conn = httplib.HTTPConnection("bugs.python.org")  
   conn.request("POST", "", params, headers)  
   response = conn.getresponse()  
   print response.status, response.reason  
   data = response.read()  
except Exception as ex:  
pass  
finally:  
conn.close()  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中发送POST请求可以使用`requests`库。首先,你需要导入`requests`模块。然后,你可以使用`requests.post()`方法来发送POST请求。你需要提供目标URL和请求的数据。例如,你可以使用以下代码发送一个POST请求: ```python import requests url = 'http://httpbin.org/post' payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post(url, data=payload) print(r.text) ``` 在这个例子中,我们使用`requests.post()`方法发送了一个POST请求到`http://httpbin.org/post`。我们提供了一个字典`payload`作为请求的数据。然后,我们打印出了响应的内容。在这个例子中,响应的内容是一个JSON格式的字符串,其中包含了我们发送的数据。 你还可以设置请求的头部信息,例如设置`Content-Type`为`application/json`。你可以使用`headers`参数来设置请求头部。以下是一个示例: ```python import requests import json url = 'https://abc/eft' headers = { 'Content-Type': 'application/json', 'User-Agent': 'SamClub/5.0.45 (iPhone; iOS 15.4; Scale/3.00)', # 其他头部信息... } data = { "perDateList": date_list, "storeDeliveryTemplateId": good_store.get('storeDeliveryTemplateId') } try: response = requests.post(url, headers=headers, data=json.dumps(data), timeout=cfg.timeout) response_data = response.json() # 处理响应数据... except Exception as e: # 处理异常... ``` 在这个示例中,我们设置了请求的头部信息,包括`Content-Type`和`User-Agent`等。我们使用`json.dumps()`方法将数据转换为JSON格式,并将其作为请求的数据发送。然后,我们可以使用`response.json()`方法将响应的内容解析为JSON格式的数据。 总结起来,使用`requests`库可以方便地发送POST请求,并且可以设置请求的头部信息和发送的数据。 #### 引用[.reference_title] - *1* *2* [python post 请求](https://blog.csdn.net/teacher20133/article/details/81560106)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [python 发送post请求](https://blog.csdn.net/lyyiangang/article/details/128275592)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值