urllib2 post请求方式,带cookie,添加请求头

#encoding = utf-8

import urllib2
import urllib

url = 'http://httpbin.org/post'
data={"name":"tom","age":22}
data=urllib.urlencode(data)

req=urllib2.Request(url,data)
html=urllib2.urlopen(req)
content = html.readlines()

print u"请求结果内容:"
print content

结果:

D:\>python test.py
请求结果内容:
['{\n', ' "args": {}, \n', ' "data": "", \n', ' "files": {}, \n', ' "form": {\n', ' "age": "22", \n', ' "name": "tom"\n', ' }, \n', ' "headers": {\n', ' "Accept-Encoding": "identity", \n', ' "Connection": "close", \n', ' "Content-Length": "15", \n', ' "Content-Type": "application/x-www-form-urlencoded", \n', ' "Host": "httpbin.org", \n', ' "User-Agent": "Python-urllib/2.7"\n', ' }, \n', ' "json": null, \n', ' "origin": "119.123.179.3", \n', ' "url": "http://httpbin.org/post"\n', '}\n']

 

添加cookie,带请求头的方式:

#encoding = utf-8

import urllib2,urllib
import cookielib

url="http://www.renren.com/ajaxLogin"
#定义一个容器,然后定义带cookie的模板,再定义一个实际的post请求
#创建cj的cookie容器
cj=cookielib.CookieJar()
#用容器创建一个带有cookie的请求模板
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
#将要post发出去的数据进行编码
data = urllib.urlencode({"email":"18142232233","password":"helloworld"})
request = urllib2.Request("http://www.baidu.com/",data)#post请求模板
request.add_header('User-Agent','Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1)')#添加请求头
r=opener.open(request)#使用带有cookie模板的请求模板发送post请求
print u"获取到的cookie为:"
print cj

print u"请求返回的第一行数据"
print r.readline()

 

 结果:

D:\>python test.py
获取到的cookie为:
<CookieJar[<Cookie BAIDUID=F86188C1F6E5F40C55BE223372AEDCCD:FG=1 for .baidu.com/>, <Cookie BDSVRTM=0 for www.baidu.com/>]>
请求返回的第一行数据
<!DOCTYPE html>

 

转载于:https://www.cnblogs.com/xiaxiaoxu/p/10274704.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值