zoukankan      html  css  js  c++  java
  • 用python做自己主动化測试--对server端的自己主动化測试(3)-很多其它http client实例

    上一篇中仅仅是实现了一个非常easy的http client功能,request还提供了keep alive, SSL, 多文件上传,cookie 管理功能,http requests头管理等丰富的功能,仅仅要你浏览器实现的功能,requests里面都支持。

    #!/usr/bin/env python
    #coding=utf-8
    
    import requests
    
    def login_douban(username, passwd):
        post_data={'source':'index_nav','form_email':username,'form_password':passwd}
        request_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0"}
        response=requests.post("http://www.douban.com/accounts/login", data=post_data,headers=request_headers)
        if u"小王子" in response.text:
            print "Login successful"
            return  response
        else:
            print "Login failed"
            print response.text
            return  False
    
    def say_something(login_cookie):
        post_data={'ck':'ynNl','rev_title':u'发福利','rev_text':u'楼主是标题党','rev_submit':u'好了,发言'}
        response=requests.post("http://www.douban.com/group/beijing/new_topic", data=post_data,cookies=login_cookie)
        if response.url=="http://www.douban.com/group/beijing/":
            print "post new content successfully"
            return  True
        else:
            print "Post content fail"
            return  False
    
    login_response=login_douban(your_usename,your_passwd)
    say_something(login_response.cookies)

    request_headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0"}, 这一行的目的是为了模拟这个请求是FireFox发出来的,非常多站点为了屏蔽爬虫,会通过User-Agent这个字段来屏蔽,当然如今大型站点应该会用更高级的手段来屏蔽爬虫,假设不设置这个User-Agent, requests发出去的请求,User-Agent的值是python-requests/2.3.0 CPython/2.7.3 Windows/7 。


    say_something这个函数没測试了,刚才我频繁的调试,豆瓣要我输入登陆验证码了,有问题这里留言,我过段时间在调试。


    关于cookie, session管理这块,假设是在同一个函数里面,request自己主动管理了session,不须要额外的处理,

    session = requests.Session()
    session.post("http://www.douban.com/accounts/login", data=post_data,headers=request_headers)
    session.post("http://www.douban.com/group/beijing/new_topic", data=post_data)

    这样就能够发帖成功。


    看到这里大家一定会想到selenium,是不是和requests一样的? requests更擅长于无UI接口測试,selenium更擅长于有UI的web測试。

  • 相关阅读:
    Toolbar Painter 工具条制作
    编程实现Windows瞬间关机
    如何在应用程序中修改本地环境变量
    据磁力链获得BT种子
    熟练使用NTFS的文件链接技术
    js中实现页面跳转
    keychain 多应用共享数据
    得到bundle seed id
    shell 基础 $(cd `dirname $0`;pwd)
    解决iOS应用内购买报错:invalidProductIdentifiers
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4048752.html
Copyright © 2011-2022 走看看