ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python-使用http.client登录网站

2019-11-11 06:05:46  阅读:314  来源: 互联网

标签:python-3-x python-requests httpconnection http-client python


我正在尝试使用以下代码在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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有