python類比瀏覽器登陸

來源:互聯網
上載者:User

標籤:

 

#! /usr/bin/env python# -*-coding:utf-8 -*-import urllibimport urllib2import cookielibclass NetRobot:    def __init__(self, baseurl):        self.cj = cookielib.CookieJar()        self.baseurl = baseurl        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))        urllib2.install_opener(self.opener)        def getData(self,username,password,**data):        print ‘origin data:‘,data        self.opener.open(self.baseurl)        try:            data[‘csrfmiddlewaretoken‘] = [x.value for x in self.cj if "csrftoken"==x.name][0] #用於Django開啟csrf中介軟體時        except:            pass        data[‘username‘]=username        data[‘password‘]=password        return data    def login(self,follow_up_url, username,password,**others):        print        print ‘-‘*25,‘login...‘,‘-‘*25        login_url = self.baseurl + follow_up_url        data = self.getData(username, password, **others)        post_data = urllib.urlencode(data)        print post_data        header = {‘User-Agent‘:‘Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)‘}  #假裝是瀏覽器        request = urllib2.Request(login_url, post_data, header)        #構造post請求        try:            self.opener.open(request)                        #提交請求            print ‘^‘*25,‘login success‘,‘^‘*25        except:            print ‘!‘*25,‘login failure‘,‘!‘*25        print    def visit(self, follow_up_url):        request = urllib2.Request(self.baseurl + follow_up_url)        content = self.opener.open(request)        print content.read()if __name__ == ‘__main__‘:    nr = NetRobot(‘http://192.168.1.100‘)          #指定網站根路徑    nr.login(‘/login/‘, ‘user‘, ‘password‘, hidRem=‘‘)  #此處假設需要額外的的hiRem參數    nr.visit(‘/api/folders/15/?format=json‘)

 

python類比瀏覽器登陸

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.