Python:对多个请求使用单个登录

2024-09-22 16:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

有一些随机网站,http://www.example.com。此网站使用HTTP基本身份验证。在

我想对这个网站提出多个请求。但我不想为每个请求登录。在

我写了以下代码:

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')

上述代码获取cookie并将其用于后续请求。在

以下代码发出后续请求:

^{pr2}$

但是,opener.open抛出urllib2.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。在

顺便说一下,我看了下面的答案,但问题仍然存在。在

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


Tags: 代码httpscomhttp网站examplecookieresponse
1条回答
网友
1楼 · 发布于 2024-09-22 16:24:26

您可能想尝试requests库并使用它Session object

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

cookie将被设置为您的会话cookie s.cookies,您可以将此会话用于其他请求。在

相关问题 更多 >