登录网站使用,而不是http.client
问题描述:
我试图登录到使用下面的代码使用Python中urllib
网站的urllib:登录网站使用,而不是http.client
import urllib.parse
import urllib.request
headers = {"Content-type": "application/x-www-form-urlencoded"}
payload = urllib.parse.urlencode({"username": "USERNAME-HERE",
"password": "PASSWORD-HERE",
"redirect": "index.php",
"sid": "",
"login": "Login"}).encode("utf-8")
request = urllib.request.Request("https://osu.ppy.sh/forum/ucp.php?mode=login", payload, headers)
response = urllib.request.urlopen(request)
data = response.read()
# print the HTML after the request
print(bytes(str(data), "utf-8").decode("unicode_escape"))
我知道,一个共同的建议是只使用请求库,并且我尝试了这一点,但我特别想知道如何在不使用请求的情况下执行此操作。
我正在寻找可以用下面的代码,成功登录到使用http.client
站点复制行为:
import urllib.parse
import http.client
headers = {"Content-type": "application/x-www-form-urlencoded"}
payload = urllib.parse.urlencode({"username": "USERNAME-HERE",
"password": "PASSWORD-HERE",
"redirect": "index.php",
"sid": "",
"login": "Login"})
conn = http.client.HTTPSConnection("osu.ppy.sh")
conn.request("POST", "/forum/ucp.php?mode=login", payload, headers)
response = conn.getresponse()
data = response.read()
# print the HTML after the request
print(bytes(str(data), "utf-8").decode("unicode_escape"))
在我看来,该urllib
代码不是“提供”的有效载荷,而http.client
代码是。
我似乎能够“传递”有效载荷,因为提供了错误的密码,并且用户名可以保证来自服务器的响应,但是提供正确的用户名和密码似乎没有效果。
任何见解?我可以忽略一些东西吗
答
添加cookie罐,并采取了标题为它们不需要与urllib
:
import http.cookiejar
import urllib.parse
import urllib.request
jar = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
payload = urllib.parse.urlencode({"username": "USERNAME-HERE",
"password": "PASSWORD-HERE",
"redirect": "index.php",
"sid": "",
"login": "Login"}).encode("utf-8")
response = opener.open("https://osu.ppy.sh/forum/ucp.php?mode=login", payload)
data = response.read()
# print the HTML after the request
print(bytes(str(data), "utf-8").decode("unicode_escape"))
我想你的代码运行,我得到预期的结果(您指定的密码不正确...) 。这意味着有效载荷已交付。如果填写正确的用户名/密码,你会得到什么回应? – Qeek
@Qeek我也看到你提到的行为,但是当给出正确的用户名和密码时,该网站仍然表现得像我还没有登录(“Welcome,guest!”而不是“Welcome,!”)。也许在初始有效载荷交付后登录不会持久?我需要使用Cookie吗? –