美文网首页
Python模拟登录,302跳转后获取cookie

Python模拟登录,302跳转后获取cookie

作者: Chting | 来源:发表于2023-02-23 17:54 被阅读0次
    import requests
    import os
    import json
    from lxml import etree
    
    def logpus(text):
        f = open("demofile2.html", "w",encoding="utf-8")
        f.write(text)
        f.close()
    
    headers = {
        # 在浏览器中,network查看
        'Content-Type': 'application/x-www-form-urlencoded',
        'Origin': 'https://typeset.io',
        'Referer': 'https://typeset.io/accounts/login/',
        'sec-ch-ua-platform': 'Windows',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.78',
    }
    session = requests.session()
    url = "https://typeset.io/accounts/login/"
    
    ##先获取csrfmiddlewaretoken
    resqonse =session.get(url,headers=headers,allow_redirects=False)
    # location = resqonse.headers['Location']
    # print(resqonse.headers)
    page_text = resqonse.text
    #构造一个etree对象
    tree=etree.HTML(page_text)
    csrfmiddlewaretoken = tree.xpath('//input[@name="csrfmiddlewaretoken"]/@value')[0]
    print("csrfmiddlewaretoken: "+csrfmiddlewaretoken)
    print("\n")
    
    data = {
        "login":"zhuxuerong215@163.com",
        "password":"zbz19910101",
        "csrfmiddlewaretoken":csrfmiddlewaretoken,
    }
    loginResqonse = session.post(url,data=data,headers=headers,allow_redirects=False)
    cookie = session.cookies
    
    
    cookie_disc = cookie.get_dict()
    print("\n")
    print(cookie_disc)
    print("\n")
    
    mylibrary = "https://typeset.io/library"
    msgResqonse = session.get(mylibrary)
    page_text = msgResqonse.text
    logpus(page_text);
    #构造一个etree对象
    tree = etree.HTML(page_text)
    script = tree.xpath('//script[@id="__NEXT_DATA__"]/text()')[0]
    
    print(script)
    
    
    
            
    
    

    相关文章

      网友评论

          本文标题:Python模拟登录,302跳转后获取cookie

          本文链接:https://www.haomeiwen.com/subject/ixktldtx.html