requests.session登录样例+图形验证

requests.session登录案例+图形验证

import json
import random
import re, requests, time
from lxml import etree
from faker import Factory
from PIL import Image
import pytesseract
from hashlib import md5


class Wkaskci(object):
    def __init__(self):
        self.session = requests.session()

    def img_code(self):
        headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                   "Host": "user.askci.com",
                   "Origin": "https://user.askci.com",
                   "Referer": "https://user.askci.com/account/login?isQuit=1",
                   'User-Agent': Factory.create().user_agent()}

        self.session.get(url="https://user.askci.com/Account/LogIn/", headers=headers)
        r = self.session.get('https://user.askci.com/Tool/GeneragteCode4Login').content
        with open('./img_code.png', 'wb') as f:
            f.write(r)
        while True:
            im = Image.open(r'D:\Desktop\python\wkaskci\img_code.png')
            num = pytesseract.image_to_string(im)
            num = "".join(num.split())
            if len(num) == 5:
                print('验证码:', num)
                break
        return str(num)

    def encrypt_md5(self, password):
        for x in range(5):
            # 创建md5对象
            new_md5 = md5()
            # 这里必须用encode()函数对字符串进行编码,不然会报 TypeError: Unicode-objects must be encoded before hashing
            new_md5.update(password.encode(encoding='utf-8'))
            # 加密
            password = new_md5.hexdigest()
        print("原密码加密:{}".format(password))
        return password

    def login(self):
        data = {
            "ThePhone": "账号",
            "ThePassword": self.encrypt_md5('密码'),
            "TheCode": self.img_code(),
            "phoneCode": "",
            "returnUrl": "",
        }
        r = self.session.post(url='https://user.askci.com/Account/LogOn/', data=data).content.decode()
        r = json.loads(r)
        if r['Flag'] == 1:
            print(r) 
            print('登录成功')
        else:
            self.login()

    def run(self):
        self.login()


if __name__ == '__main__':
    wk = Wkaskci()
    wk.run()

你可能感兴趣的:(爬虫,python,爬虫)