爬虫解决验证码,用requests创建session会话对象

import requests
from urllib import request
import re

# 创建一个回话
session=requests.session()
#请求携带的表单数据
form={
    'form_email':'',
    'form_password':''
}

def login():
    login_url='https://accounts.douban.com/login'
    form = {
        'form_email': '',
        'form_password': ''
    }
    #发送请求
    response=session.post(login_url,data=form)
    # 设置编码
    response.encoding=response.apparent_encoding
    # 获取数据
    html=response.text
    # print(html)
    if  'captcha_image' in html:
        # 编译正则(获取图片下载链接地址)
        captcha_pat=re.compile(r'id="captcha_image" src="(.+?)"')
        #搜索数据(图片)
        res=captcha_pat.search(html)
        #获取数据(图片链接)
        captcha=res.group(1)
        #写入图片文件    
        request.urlretrieve(captcha,'douban.png')

        #编译正则(获取隐藏验证码数据)
        id_pat=re.compile(r'name="captcha-id" value="(.+?)"')
        #查找验证码数据
        res=id_pat.search(html)
        #获取验证码数据
        captcha_id=res.group(1)
        print(captcha,captcha_id)

        captcha=input('输入验证码:')#输入内容(图片验证码)
        #存入form中
        form['captcha-solution']=captcha#等于当前验证码的图片
        form['captcha-id']=captcha_id#等于输入的内容
        # 再次访问页面,携带验证码数据
        response=session.post(login_url,data=form)
        response.encoding=response.apparent_encoding#设置编码
        # 获取数据
        html=response.text
        # 判断
        if '个人主页' in html:
            #个人主页的链接
            home_url="https://www.douban.com/mine/"
            #获取session
            response=session.get(home_url)
            print(response.url)
            print('登录成功')
            return response
    else:
        print('登录成功')

def update_sign(response,sign):
    edit_url=response.url+'edit_signature'
    #进行代替,替换
    edit_url=edit_url.replace('/people','/j/people/')
    print(edit_url)
    html=response.text#个人页面
    ck_pat=re.compile(r'name="ck" value="(.+?)"')#编译正则
    res=ck_pat.search(html)#搜索数据
    ck=res.group(1)#获取数据
    #更改数据
    form={
        'ck':ck,#发布的验证
        'signature':sign#发布的内容
    }
    resp=session.post(edit_url,data=form)#携带数据,从新访问
    resp.encoding=resp.apparent_encoding#设置编码
    print(resp.text)


if __name__ == '__main__':
    # 调用
    response=login()
    while True:
        choice=input('请选择:')
        if choice == '1':#进行更改
            sign=input('输入签名:')
            # 调用,闯入数据
            update_sign(response,sign)
        elif choice == 'q':#退出
            break

猜你喜欢

转载自blog.csdn.net/ren_ger/article/details/81190910