zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    12
    11-常用模块
    10-异常处理
    C#程序关闭时怎么关闭子线程
    [转]Android加载图片堆栈溢出
    [转]JS弹出确认/取消对话框
    [整理]获取当前页面的网址
    C/C++多参数处理
    图标素材网站收集
    PHP "Warning: Unknown: failed to open stream: Permission denied in Unknown on line 0" 错误
  • 原文地址:https://www.cnblogs.com/laod/p/13100637.html
Copyright © 2011-2022 走看看