概述

需要使用playwright在chrome中打开chrome://system/,然后点开插件按钮,查看所有的插件内容,过滤出需要的内容。

代码实现

  1. import logging.config
  2. import os
  3. import re
  4. import time
  5. from playwright.sync_api import sync_playwright
  6. logging.config.fileConfig("logger.ini")
  7. logger = logging.getLogger()
  8. configs = None
  9. # 这个是录屏插件的部分名称,用于模糊匹配的
  10. plugin_name = 'screen'
  11. # 用于保存录屏插件pid的文件名称
  12. plugin_pid_file = ''
  13. def getExtensionId(extensionName):
  14. extensionName = extensionName.lower()
  15. """
  16. 根据插件名称,获取自定义插件的id
  17. :param extensionName:
  18. :return:
  19. """
  20. if not os.path.exists(configs['ext_chrome_path']):
  21. logger.warning('chrome not exist, please check. path:%s' % configs['ext_chrome_path'])
  22. return
  23. url = 'chrome://system/'
  24. with sync_playwright() as playwright:
  25. browser = playwright.chromium.launch_persistent_context(configs['chrome_user_data_dir'],
  26. args=configs['chrome_parameters'],
  27. headless=configs['record_headless'],
  28. executable_path=configs['ext_chrome_path'],
  29. ignore_default_args=['--enable-automation'])
  30. print(f'start to load page,{time.time()}')
  31. page = browser.new_page()
  32. # 打开指定网址
  33. page.goto(url)
  34. # 等待按钮被渲染出来
  35. page.wait_for_selector('id=extensions-value-btn')
  36. # 点击按钮
  37. page.click('id=extensions-value-btn')
  38. # 等待div被显示出来
  39. page.wait_for_selector('id=extensions-value')
  40. # 获取div内部的文本值
  41. text = page.inner_text('id=extensions-value')
  42. print(f'total plugin info: {text}')
  43. if text:
  44. for line in text.splitlines():
  45. (pid, name, version) = re.split(r'\s:\s', line)
  46. if extensionName in name.lower():
  47. return (pid, name)
  48. def get_extension_pid(my_configs):
  49. """
  50. 获取录屏插件的pid,作为chrome参数使用
  51. :return:
  52. """
  53. global configs, plugin_pid_file
  54. configs = my_configs
  55. plugin_pid_file = configs['plugin_pid_file']
  56. if not has_pid():
  57. logger.info('screen plugin id not exist, need to generate')
  58. generate_pid()
  59. logger.info(f'success to generate screen plugin')
  60. else:
  61. logger.info('screen plugin pid exist, just return')
  62. my_pid = ''
  63. with open(plugin_pid_file, 'r') as f:
  64. my_pid = f.readline()
  65. logger.info(f'final return screen plugin id: {my_pid}')
  66. return my_pid
  67. def has_pid():
  68. """
  69. 判断当前是否存在录屏插件的pid,不存在的话,则需要生成
  70. :return:
  71. """
  72. return os.path.exists(plugin_pid_file)
  73. def generate_pid():
  74. logger.info('start to get custom plugin id')
  75. (pid, pname) = getExtensionId(plugin_name)
  76. logger.info(f'screen plugin id: {pid}')
  77. logger.info(f'screen plugin name: {pname}')
  78. with open(plugin_pid_file, 'w') as f:
  79. f.write(pid)
  80. if __name__ == "__main__":
  81. generate_pid()