编程语言
首页 > 编程语言> > python-使用http.client登录网站

python-使用http.client登录网站

作者:互联网

我正在尝试使用以下代码在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代码没有“传递”有效负载,而Requests代码却是.

有什么见解吗?我在俯视什么吗?

编辑:添加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

解决方法:

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

标签:python-3-x,python-requests,httpconnection,http-client,python
来源: https://codeday.me/bug/20191111/2018085.html