美文网首页
Python实现模拟浏览器登录操作

Python实现模拟浏览器登录操作

作者: Daisy丶 | 来源:发表于2018-01-29 15:06 被阅读471次

    最近帮朋友写一个脚本,用来刷新信息。具体的操作就是模拟用户登录之后,在用户的信息发布页面,对每一个页面,在固定的时间间隔内点击刷新按钮。我使用Python3 和 Requests库来实现了这个功能。Requests 是用基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。我们使用他的原因是他能更加方便的保存Session信息。

    流程:

    1. 解析页面表单构成,获取请求的头信息
    2. 模拟浏览器登录
    3. 保存Session,进入用户中心。
    4. 解析页面,获取需要更新的页面。
    5. 对每个页面的刷新按钮发起请求。
    6. 休眠计时。

    解析登录页面:

    首先打开登录页面,通过chrome来审查表单结构与Request Headers的信息。根据信息来构建登陆时的提交头文件与登录信息。

    模拟浏览器发起请求的头信息:

        headers1 = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://www.shicheng.one',
            'Referer': 'https://www.shicheng.one/user/login',
            'Upgrade-Insecure-Requests': '1'
        }
    

    用户登录表单,其中csrf是用户每次发起请求时动态生成的:

        payload = {
            "LoginForm[username]": "username",
            "LoginForm[password]": "password",
            "LoginForm[rememberMe]": 0,
            "_csrf": "csrf"
        }
    

    动态获取CSRF

    当我们每次向目标地址发起一个Request请求时,表单内部会动态生成一个csrf口令,并将其与html页面内容一起返回,因此我们可以通过解析页面内容来获取csrf口令。这里我们使用HTMLlParser来找到_csrf标签对应的内容。

    class Myparser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
            self.values = 0
    
        def handle_starttag(self, tag, attrs):
            def _attr(attrlist, attrname):
                for each in attrlist:
                    if attrname == each[0]:
                        return each[1]
                return None
    
            if tag == 'input' and _attr(attrs, 'name') == '_csrf':
                self.values = _attr(attrs, 'value')
    
    
    def get_csrf(login):
        data = login.text
        par = Myparser()
        par.feed(data)
    
        return par.values
    
    

    模拟浏览器登录

    我们使用requests库实例化一个会话,然后使用我们构建的表单内容与Headers来进行登录,其中csrf是动态获取的。这样我们的信息就会被保存在这个对象中。

     session_requests = requests.Session()
    
    login = session_requests.get(login_url)
    csrf = get_csrf(login)
    payload["_csrf"] = csrf
    login = session_requests.post(login_url, data=payload, headers=headers1)
    

    为了检查是否请求成功,可以查看请求发回的状态码

    login.status_code
    

    解析用户页面并发起请求

    在访问用户信息页面并刷新时,我们使用下面的头文件发起请求,其中referer是根据我们要访问的地址动态更新的。

        headers2 = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': '',
            'Upgrade-Insecure-Requests': '1'
        }
    

    home是我们要访问的用户信息页面,我们从中提取列表中的网址,并解析出id。其中每个页面的内的刷新按钮是与对应的js相关联的,因为我们通过前面固定的网址与id动态构建出刷新请求的地址。最后我们按照刷新的cd,使用更新后的Headers发起刷新请求。

       getstat = session_requests.get(home)
    
        urls = list(set(re.findall(pattern1, getstat.text)))
        ids = [re.findall(pattern2, url)[1] for url in urls]
        refresh = ["https://www.shicheng.one/node/refresh?id=" + i for i in ids]
    
        while True:
            for r, url in zip(refresh, urls):
                headers2['Referer'] = url
                getstat = session_requests.get(r, headers=headers2)
    
            print('Refresh at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            time.sleep(6 * 60 * 60)
    

    完整代码

    # coding: utf8
    import re
    import time
    import requests
    from html.parser import HTMLParser
    
    
    class Myparser(HTMLParser):
        def __init__(self):
            HTMLParser.__init__(self)
            self.values = 0
    
        def handle_starttag(self, tag, attrs):
            def _attr(attrlist, attrname):
                for each in attrlist:
                    if attrname == each[0]:
                        return each[1]
                return None
    
            if tag == 'input' and _attr(attrs, 'name') == '_csrf':
                self.values = _attr(attrs, 'value')
    
    
    def get_csrf(login):
        data = login.text
        par = Myparser()
        par.feed(data)
    
        return par.values
    
    
    def run():
        print("Press 'Ctrl+C' to exit...")
    
        rule1 = r'http://www\.shicheng\.one/s1/\d+'
        pattern1 = re.compile(rule1)
        pattern2 = re.compile(r'\d+')
    
        login_url = 'https://www.shicheng.one/user/login'
        home = 'https://www.shicheng.one/member/index?id=16973'
    
        headers1 = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://www.shicheng.one',
            'Referer': 'https://www.shicheng.one/user/login',
            'Upgrade-Insecure-Requests': '1'
        }
    
        headers2 = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': '',
            'Upgrade-Insecure-Requests': '1'
        }
    
        payload = {
            "LoginForm[username]": "username",
            "LoginForm[password]": "password",
            "LoginForm[rememberMe]": 0,
            "_csrf": ""
        }
    
        session_requests = requests.Session()
    
        login = session_requests.get(login_url)
        csrf = get_csrf(login)
        payload["_csrf"] = csrf
        login = session_requests.post(login_url, data=payload, headers=headers1)
    
        getstat = session_requests.get(home)
    
        urls = list(set(re.findall(pattern1, getstat.text)))
        ids = [re.findall(pattern2, url)[1] for url in urls]
        refresh = ["https://www.shicheng.one/node/refresh?id=" + i for i in ids]
    
        while True:
            for r, url in zip(refresh, urls):
                headers2['Referer'] = url
                getstat = session_requests.get(r, headers=headers2)
    
            print('Refresh at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            time.sleep(6 * 60 * 60)
    
    
    if __name__ == '__main__':
        run()
    
    

    相关文章

      网友评论

          本文标题:Python实现模拟浏览器登录操作

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