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

时间:2016-08-19 20:50:10

标签: python session cookies urllib2 urllib

有一些随机网站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并将其用于后续请求。

以下代码生成后续请求:

def getHTMLSourceCode(ID):        

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

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

但是,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

1 个答案:

答案 0 :(得分:0)

您可以尝试String userHome = System.getProperty("user.home"); String path = userHome + "\\Downloads\\quotes.csv"; File f = new File(path); BufferedReader br = new BufferedReader(new FileReader(f)); 库并使用它Session object

requests

Cookie将设置为您的会话Cookie s = requests.Session() s.auth = (username, password) s.get(homeURL) ,您可以将此会话用于其他请求。