Python 3.4 带有 cookie 的 HTTP POST 请求

Python 3.4 HTTP POST request with cookies

我在构建一个方法时遇到问题,该方法将使用 headers 和数据(用户名和密码)执行 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?

经过一些研究,数据似乎不能作为参数直接传递给 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)