Python模拟登陆 —— 征服验证码 4 果壳

浏览: 1482

作者:SeanCheney

链接:https://www.jianshu.com/p/bb34f085a5ce

來源:简书


果壳的特殊之处是有隐藏的随机token令牌,

登录界面

查看源代码:

隐藏的令牌

import sys
import os.path
import http.cookiejar

import requests
from bs4 import BeautifulSoup

login_url = ("http://www.guokr.com/sso/"
"?suppress_prompt=1&lazy=y&success=http%3A%2F%2Fwww.guokr.com%2F")
session = requests.session()
session.cookies = http.cookiejar.LWPCookieJar()
# Opening ``login_url`` will redirect us to the actual page where we
# can retreive some necessary data and make post requests.
resp = session.get(login_url) # We'll make post requests to ``resp.url``.
soup = BeautifulSoup(resp.text, "html.parser")


def get_csrf_token():
"""
:rtype: str
"""

csrf_token = soup.find(id="csrf_token").attrs["value"]
return csrf_token


def get_captcha_rand():
"""
:rtype: str
"""

captcha_rand = soup.find(id="captchaRand").attrs["value"]
return captcha_rand


def get_captcha_img():
"""
:rtype: NoneType
"""

captcha_img_url = soup.find(id="captchaImage").attrs["src"]
resp = session.get(captcha_img_url, stream=True)
with open("captcha_img.png", "wb") as f:
for chunk in resp.iter_content(chunk_size=128):
f.write(chunk)


def login(url, username, password, csrf_token, captcha, captcha_rand):
"""
:type url: str
:type username: str
:type password: str
:type csrf_token: str
:type captcha: str
:type captcha_rand: str
:rtype: NoneType
"""

payload = {
"username": username,
"password": password,
"csrf_token": csrf_token,
"captcha": captcha,
"captcha_rand": captcha_rand,
"permanent": "y"
}
try:
resp = session.post(url, data=payload)
resp.raise_for_status()
except requests.exceptions.HTTPError:
soup = BeautifulSoup(resp.text, "html.parser")
error = soup.find(class_="login-error")
sys.exit(error.string.strip())


def is_logged_in():
"""
:rtype: bool
"""

url = "http://www.guokr.com/settings/profile/"
resp = session.get(url)
if "gheaderSettings" in resp.text:
return True
else:
return False


def main():
"""Run the program."""
csrf_token = get_csrf_token()
captcha_rand = get_captcha_rand()
get_captcha_img()
username = input("Enter username> ")
password = input("Enter password> ")
captcha = input("Enter CAPTCHA ({})> "
.format(os.path.abspath("captcha_img")))
login(resp.url, username, password, csrf_token, captcha, captcha_rand)
if is_logged_in():
print("You are now logged in.")
else:
print("Hmm... Something is wrong.")
print("Cookies are save in {}".format(os.path.abspath("cookies")))
session.cookies.save("cookies", ignore_discard=True)


if __name__ == "__main__":
main()
推荐 0
本文由 Python爱好者社区 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册