【问题标题】:Python 3.4 HTTP POST request with cookies带有 cookie 的 Python 3.4 HTTP POST 请求
【发布时间】:2015-01-30 06:43:50
【问题描述】:

我在构建一个方法时遇到问题,该方法将使用标头和数据(用户名和密码)执行 HTTP POST 请求并检索生成的 cookie。

这是我迄今为止的最新尝试:

def do_login(username, password):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
               "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
    cj = http.cookiejar.CookieJar()
    req = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    data = {"Username": username, "Password": password}
    req.open("http://example.com/login.php", data)

但每当我尝试更改方法时,我都会不断收到异常。另外,响应 cookie 会存储在 CookieJar cj 中,还是仅用于发送请求 cookie?

【问题讨论】:

    标签: python cookies


    【解决方案1】:

    经过一番研究,似乎无法将数据直接作为参数传递给req.open,需要将其转换为 URL 编码的字符串。这是对我有用的解决方案:

    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36",
               "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"}
    
    cj = http.cookiejar.CookieJar()
    req = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    req.addheaders = list(headers.items())
    
    # The data should be URL-encoded and then encoded using UTF-8 for best compatilibity
    data = urllib.parse.urlencode({"Username": username, "Password": password}).encode("UTF-8")
    res = req.open("http://example.com/login.php", data)
    

    【讨论】:

      猜你喜欢
      • 2014-05-26
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多