Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用http.client登录到网站_Python_Python 3.x_Python Requests_Httpconnection_Http.client - Fatal编程技术网

Python 使用http.client登录到网站

Python 使用http.client登录到网站,python,python-3.x,python-requests,httpconnection,http.client,Python,Python 3.x,Python Requests,Httpconnection,Http.client,我正在尝试使用以下代码在Python中使用http.client登录到一个网站: import urllib.parse import http.client payload = urllib.parse.urlencode({"username": "USERNAME-HERE", "password": "PASSWORD-HERE", "redirect":

我正在尝试使用以下代码在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"))
我知道一个常见的建议是只使用Requests库,我已经尝试过了,但我特别想知道如何在不使用Requests的情况下做到这一点

我正在寻找的行为可以通过以下代码复制,这些代码使用请求成功登录到站点:

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代码并没有“传递”有效负载,而请求代码则是

有什么见解吗?我是不是忽略了什么


编辑:添加
conn.set\u 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

由于您正在对有效负载进行URL编码,因此必须发送标题:
application/x-www-form-urlencoded

使用HTTPConnection运行。设置调试级别(1)。。。您还需要发送一个“Content type:'application/json”标题。@CoreyGoldberg我修改了问题,请查看编辑。我没有注意到您正在对有效负载进行URL编码。所以标题需要是'application/x-www-form-urlencoded``@CoreyGoldberg Works!非常感谢你!我只是加上它作为答案。请接受