zoukankan      html  css  js  c++  java
  • 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
    请求结果内容:
    ['{ ', ' "args": {}, ', ' "data": "", ', ' "files": {}, ', ' "form": { ', ' "age": "22", ', ' "name": "tom" ', ' }, ', ' "headers": { ', ' "Accept-Encoding": "identity", ', ' "Connection": "close", ', ' "Content-Length": "15", ', ' "Content-Type": "application/x-www-form-urlencoded", ', ' "Host": "httpbin.org", ', ' "User-Agent": "Python-urllib/2.7" ', ' }, ', ' "json": null, ', ' "origin": "119.123.179.3", ', ' "url": "http://httpbin.org/post" ', '} ']

    添加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>

  • 相关阅读:
    第五次实验报告
    第四次实验报告
    [_UICascadingTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
    真机测试时出现 could not find developer disk image问题
    UItableview正在滚动的时候进行操作容易出问题
    NSArray NSMutableArray 初始化
    日志报错Can't add self as subview
    设置statusBar状态栏颜色
    网站视频url地址获取
    ios9 xcode7以后编译需要进行的几项设置
  • 原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10274704.html
Copyright © 2011-2022 走看看