Python3 实现带cookie登陆网站--自动

from urllib import request, parse
from http import cookiejar

# 创建cookiejar的实例
cookie = cookiejar.CookieJar()
# 生成cookie的管理器
cookie_handler = request.HTTPCookieProcessor(cookie)
# 创建http请求管理器
http_handler = request.HTTPHandler()

# 生成https管理器
https_handler = request.HTTPSHandler()

# 创建请求管理器
opener = request.build_opener(http_handler, https_handler, cookie_handler)


def login():
    '''
     负责初次登陆
     需要输入用户名密码,用来过去登陆cookie凭证
    '''

    # 此url需要从登陆from的action属性中提取
    url = 'http://www.renren.com/PLogin.do'

    # 键值需要从登陆from的两个对应input中提取name属性
    data = {
        'email': "185807487xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        'password': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
    }

    # 把数据进行编码
    data = parse.urlencode(data)

    # 创建一个请求对象
    req = request.Request(url, data=data.encode())

    # 使用openner发起请求
    opener.open(req)



def getHomepage():
    url = 'http://www.renren.com/974598244/profile'

    # 如果已经执行了login函数,则opener自己已经包含了对应的cookie值
    rsp = opener.open(url)
    html = rsp.read().decode()
    with open("rsp.html", 'w', encoding='utf-8') as f :
        f.write(html)

if __name__ == '__main__':
    login()
    getHomepage()
原文地址:https://www.cnblogs.com/laod/p/13100637.html