• Selenium和Requests搭配使用


    前要

    之前有提过, 用selenium控制本地浏览器, 提高拟人化,但是效率比较低,今天说一种selenium和requests搭配使用的方法
    注意: 一定要先了解怎么远程控制浏览器,之后再按照这个来

    selenium控制本地浏览器(二选一)
    https://blog.csdn.net/weixin_44388373/article/details/121989842
    https://blog.csdn.net/weixin_45081575/article/details/112621581

    1. CDP

    CDP 全称为 Chrome Devtools-Protocol

    通过执行 CDP 命令,可以在网页加载前运行一段代码,进而改变浏览器的指纹特征
    允许使用工具来检测、检查、调试和分析 Chromium、Chrome 和其他基于 Blink 的浏览器。

    2. 通过requests控制浏览器

    看这里!!!
    这里值得注意是安装 websocket 模块,要按照这以下顺序

    1. pip install webscoket
    2. pip install websocket-client
    # 之前的代码启动浏览器,selenium调用没问题
    # 调用方式1
    "C:\Program Files\Google\Chrome\Application\chrome.exe"  --remote-debugging-port=9222 --user-data-dir="随便找个空文件夹路径"
    
    # 调用方式2
    start chrome --remote-debugging-port=9222 --user-data-dir="C:\Users\1\Desktop\chrome"
    
    # 代码调用
    import os
    os.popen('start chrome --remote-debugging-port=9222 --user-data-dir="C:\Users\1\Desktop\chrome"')
    
    # 但是如果让requests调用会出错(无权限,禁止调用)
    # 需要在语句中加入 --remote-allow-origins=* 
    import os
    os.popen('start chrome --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir="C:\Users\1\Desktop\chrome"')
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2. 1 代码一

    这里用的是 小菜欸 大佬的文章: 【Selenium】Python & Selenium 执行 CDP
    我只是摘抄了一部分, 大佬讲的更详细, 推荐各位去看看

    # 这里插入代码片
    # -*- coding: utf-8 -*-
    # @Time   : 2022-08-27 12:00
    # @Name   : py_cdp.py
    
    import json
    import requests
    import websocket
    
    
    def websocket_conn():
        # websocket_conn 连接浏览器
        resp = requests.get('http://127.0.0.1:9222/json')  # 有不懂的看上一篇文章
        assert resp.status_code == 200
        ws_url = resp.json()[0].get('webSocketDebuggerUrl')
        return websocket.create_connection(ws_url)
    
    
    def execute_cdp(conn: websocket, command: dict):
        # 执行  dp
        conn.send(json.dumps(command))
        # 接受websocket的响应,并将字符串转换为 dict()
        return json.loads(conn.recv())
    
    
    def main():
        conn = websocket_conn()
        # js = "alert('hello world')" # 弹窗 hello world
        # js = "console.log('hello world')" # 控制台打印 hello world
        js = "location.href='https://www.bilibili.com'"  # 页面跳转
        command = {
            'method': 'Runtime.evaluate',  # 处理 传进去的 expression
            'id': int(1),	# id需要传一个整型,否则会报错,可以随便填一个数字
            'params': {'expression': js}   # 要执行的js语句
        }
        resp = execute_cdp(conn, command)
        print(resp)
    
    
    if __name__ == '__main__':
        main()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    运行效果看下面动图,js代码中指定页面跳转到 B站。
    在这里插入图片描述

    2. 2 代码2

    这里用的是 合天网安实验室 的文章: 利用远程调试获取Chromium内核浏览器Cookie
    这个也只摘抄了一部分, 推荐各位去看看
    代码可以获取本地浏览器所有Cookie, 包括保存到本地的Cookie信息

    import json
    import requests
    import websocket
    # 添加以后发送如下数据包就可以成功获取Cookie
    GET_ALL_COOKIES_REQUEST = json.dumps({"id": 1, "method": "Storage.getCookies"})
    
    
    def hit_that_secret_json_path_like_its_1997():
        response = requests.get("http://127.0.0.1:9222/json")
        websocket_url = response.json()[0].get("webSocketDebuggerUrl")
        return websocket_url
    
    
    def gimme_those_cookies(ws_url):
        ws = websocket.create_connection(ws_url)
        ws.send(GET_ALL_COOKIES_REQUEST)
        result = ws.recv()
        ws.close()
        response = json.loads(result)
        print(response)
        cookies = response["result"]["cookies"]
        return cookies
    
    
    def to_cookie_dict(data):
    	# name:cookie的名称 必须有
    	# value:cookie对应的值,动态生成的, 必须有
    	# domain:服务器域名
    	# expiry:Cookie有效终止日期
    	# path:Path属性定义了Web服务器上哪些路径下的页面可获取服务器设置的Cookie
    	# httpOnly:防脚本攻击
    	# secure:在Cookie中标记该变量,表明只有当浏览器和Web Server之间的通信协议为加密认证协议时# 
    	# {'domain': '.gonggaotong.net', 'httpOnly': False, 'name': 'Hm_lpvt_5aed315e6cf23667dff3f1224c5dcb60', 'path': '/', 'secure': False, 'value': '1642657344'}
    	
    	# 筛选cookie
        if 'bilibili.com' in data['domain']:
            cookie_dict = {data['name']: data['value'], 'Domain': data['domain'], 'Path': data['path'], 'Expires': data['expires']}
            print(cookie_dict)
            return cookie_dict
    
    
    ws_url = hit_that_secret_json_path_like_its_1997()
    print(ws_url)
    data_list = gimme_those_cookies(ws_url)
    print(data_list)
    
    cookie_dict_list = [to_cookie_dict(data) for data in data_list]
    # 遍历多个cookie字典,将每个字典中的key和value格式化为key=value的字符串
    cookie_str_list = []
    for cookie_dict in cookie_dict_list:
        if cookie_dict:
            for k, v in cookie_dict.items():
                cookie_str_list.append('{}={}'.format(k, v))
    
    # 使用;将多个key=value字符串连接在一起
    cookie_str = ';'.join(cookie_str_list)
    print(cookie_str)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    获取到的Cookie
    在这里插入图片描述

    3. 通过selenium获取cookie, requests携带cookie请求

    先用selenium登录网站, 然后获取cookie, requests携带cookie访问

    import json
    import os
    from selenium.webdriver import Chrome
    import requests
    import websocket
    from selenium.webdriver.chrome.options import Options
    
    GET_ALL_COOKIES_REQUEST = json.dumps({"id": 1, "method": "Storage.getCookies"})
    
    
    def open_chrome():
        try:
            requests.get('http://127.0.0.1:9222/json')  # 有不懂的看上一篇文章
        except:
            os.popen(
                r'start chrome --remote-debugging-port=9222 --remote-allow-origins=* --user-data-dir="C:\Users\v_chewqiao\Desktop\chrome"')
        chrome_options = Options()
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
        driver = Chrome(options=chrome_options)
        return driver
    
    
    def hit_that_secret_json_path_like_its_1997():
        response = requests.get("http://127.0.0.1:9222/json")
        websocket_url = response.json()[0].get("webSocketDebuggerUrl")
        return websocket_url
    
    
    def gimme_those_cookies(ws_url):
        ws = websocket.create_connection(ws_url)
        ws.send(GET_ALL_COOKIES_REQUEST)
        result = ws.recv()
        ws.close()
        response = json.loads(result)
        cookies = response["result"]["cookies"]
        return cookies
    
    
    def to_cookie_dict(data_list):
        cookie_dict = {}
        for data in data_list:
            # 根据域名确定网站cookie
            if 'czce.com' in data['domain']:
                cookie_dict[data['name']] = data['value']
        return cookie_dict
    
    
    def update_cookie(cookie_dict):
        cookie = ''
        for key, value in cookie_dict.items():
            cookie = cookie + "{}={}; ".format(key, value)
        return cookie
    
    
    def return_cookie():
        driver = open_chrome()
        driver.delete_all_cookies()
        # driver.execute_script("window.open('http://www.czce.com.cn/','_self');")
        # time.sleep(3)
        ws_url = hit_that_secret_json_path_like_its_1997()
        data_list = gimme_those_cookies(ws_url)
        cookie_dict = to_cookie_dict(data_list)
        # cookie 转为字符串
        cookie = update_cookie(cookie_dict)
        # 或者cookie直接写入session
        # session.cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
        return cookie
    
    
    if __name__ == '__main__':
        return_cookie()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72

    结果如下:
    在这里插入图片描述

  • 相关阅读:
    推荐一个基于.NET Core 3.1开发开源的分布式任务调度系统
    C++解LeetCode225. 用队列实现栈(适合基础薄弱)
    mysql8.0安装教程与配置(最详细)操作简单
    有效学习,通过PMP考试
    以自主技术跃进的综合冲压的顶级制造商
    Android中可变帧率VRR
    C语言实现模拟 strcmp 字符串比较函数,实现字符串大小的比较
    opencv基础-印度小哥
    应急响应-文件痕迹排查
    STM32项目分享:智能家居语音系统
  • 原文地址:https://blog.csdn.net/weixin_44388373/article/details/133080171