我试图使用Python中的http.client登录到一个网站,使用以下代码:
import urllib.parse
import http.client
payload = urllib.parse.urlencode({"username": "USERNAME-HERE",
"password": "PASSWORD-HERE",
"redirect": "index.php",
"sid": "",
"login": "Login"})
conn = http.client.HTTPConnection("osu.ppy.sh:80")
conn.request("POST", "/forum/ucp.php?mode=login", payload)
response = conn.getresponse()
data = response.read()
# print the HTML after the request
print(bytes(str(data), "utf-8").decode("unicode_escape"))我知道一个常见的建议是只使用请求库,我已经尝试过了,但是我特别想知道如何在不使用请求的情况下做到这一点。
我正在寻找的行为可以使用以下代码复制,这些代码可以使用请求成功登录到站点:
import requests
payload = {"username": "USERNAME-HERE",
"password": "PASSWORD-HERE",
"redirect": "index.php",
"sid": "",
"login": "Login"}
p = requests.Session().post('https://osu.ppy.sh/forum/ucp.php?mode=login', payload)
# print the HTML after the request
print(p.text)在我看来,http.client代码不是在“传递”有效负载,而请求代码是。
有什么见解吗?我是不是忽略了什么?
编辑: the conn.set_debuglevel(1)提供了以下输出:
send: b'POST /forum/ucp.php?mode=login HTTP/1.1
Host: osu.ppy.sh
Accept-Encoding: identity
Content-Length: 70'
send: b'redirect=index.php&sid=&login=Login&username=USERNAME-HERE&password=PASSWORD-HERE'
reply: 'HTTP/1.1 200 OK'
header: Date
header: Content-Type
header: Transfer-Encoding
header: Connection
header: Set-Cookie
header: Cache-Control
header: Expires
header: Pragma
header: X-Frame-Options
header: X-Content-Type-Options
header: Server
header: CF-RAY发布于 2017-07-11 03:07:02
由于您正在对有效负载进行代码编写,所以必须发送报头:application/x-www-form-urlencoded
https://stackoverflow.com/questions/45001932
复制相似问题