2016-08-19 11 views
1

ランダムなウェブサイトがあります。http://www.example.comです。このWebサイトはHTTP基本認証を使用します。Python:複数のリクエストにシングルログインを使用

このサイトに複数のリクエストを送信します。しかし、私は各リクエストのためにログインしたくありません。

私は、次のコードを書かれている:

def loginWeb(): 
    global cookie 

    homeURL = "https://www.example.com" 
    request = urllib2.Request(homeURL) 

    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '') 
    request.add_header("Authorization", "Basic %s" % base64string) 

    response = urllib2.urlopen(request) 
    cookie = response.headers.get('Set-Cookie') 

上記のコードでは、クッキーを取り出し、後続の要求のためにそれを使用しています。

def getHTMLSourceCode(ID):   

    opener = urllib2.build_opener() 
    opener.addheaders.append(('Cookie', cookie)) 

    response = opener.open('https://www.example.com/' + trID) 
    sourceCode = response.read() 

しかし、opener.openurllib2.HTTPError: HTTP Error 401: Unauthorizedをスロー:

次のコードは、後続の要求を行います。

私はまた、次のコードを試してみましたが、これも同じエラーがスローされます。

def getHTMLSourceCode(trID):   
    request = urllib2.Request("https://www.example.com/" + trID)  
    request.add_header('cookie', cookie) 
    response = urllib2.urlopen(request) 

    sourceCode = response.read() 

    return sourceCode 

urllib2.urlopen(request)urllib2.HTTPError: HTTP Error 401: Unauthorizedをスローします。

ところで、私は答えに従っていきましたが、問題は依然として続きます。あなたはrequestsライブラリを試してみて、クッキーはセッションクッキーs.cookiesに設定され、あなたができるSession object

s = requests.Session() 
s.auth = (username, password) 
s.get(homeURL) 

それを使用したい場合があり

Python urllib2, basic HTTP authentication, and tr.im

Keeping a session in python while making HTTP requests

python: urllib2 how to send cookie with urlopen request

答えて

0

othのためにこのセッションを使用するer要求。

関連する問題