selenium.chrome怎么写扩展拦截或转发请求?

Selenium WebDriver 是一组开源 API,用于自动测试 Web 应用程序,利用它可以通过代码来控制chrome浏览器!

有时候我们需要mock接口的返回,或者拦截和转发请求,今天就来实现这个功能。

代码已开源: https://github.com/yuzd/OpenQA.Selenium.Chrome.Fiddler

nuget

OpenQA.Selenium.Chrome.Fiddler

开始coding

我们新创建一个功能:OpenQA.Selenium.Chrome.Fiddler

一个chrome扩展 最起码有2个文件

·manifest.json

· background.js

稍微解释一下:

manifest.json 是来描述chrome扩展的

python 复制代码
{
      "version": "1.0.0",
      "manifest_version": 2,
      "name": "Chrome Fiddler",
      "permissions": [
          "proxy",
          "tabs",
          "unlimitedStorage",
          "storage",
          "<all_urls>",
          "webRequest",
          "webRequestBlocking"
      ],
      "background": {
          "scripts": ["background.js"]
   },
      "minimum_chrome_version":"22.0.0"
  }

background.js 是逻辑处理模块

因为拦截api 或者 转发 需要用的chrome的api

python 复制代码
chrome.webRequest.onBeforeRequest.addListener(
     function(details) {
        //逻辑处理
     },
     { urls: ['<all_urls>']},
     ['blocking', 'extraHeaders', 'requestBody']
  );

这个api的函数 接收的details参数:

  ·details.url 是api的接口

  函数的返回

  · {cancel:true} 拦截请求

  · {redirectUrl:''} 转发到指定url

**  写selenium.chrome插件**

  新建一个netstand工程,然后引用

  · Selenium.WebDriver

python 复制代码
/// <summary>
  /// Add Fiddler extention
  /// </summary>
  /// <param name="options">Chrome options</param>
  /// <param name="fiddlerOption">Proxy host</param>
  public static void AddFiddler(this ChromeOptions options, FiddlerOption fiddlerOption)
  {
      var backgroundProxyJs = ReplaceTemplates(background_js, fiddlerOption);
      if (!Directory.Exists("Plugins"))
          Directory.CreateDirectory("Plugins");
      var guid = Guid.NewGuid().ToString();
      var manifestPath = $"Plugins/manifest_{guid}.json";
      var backgroundPath = $"Plugins/background_{guid}.js";
      var archiveFilePath = $"Plugins/proxy_auth_plugin_{guid}.zip";
      File.WriteAllText(manifestPath, manifest_json);
      File.WriteAllText(backgroundPath, backgroundProxyJs);
      using (var zip = ZipFile.Open(archiveFilePath, ZipArchiveMode.Create))
      {
          zip.CreateEntryFromFile(manifestPath, "manifest.json");
          zip.CreateEntryFromFile(backgroundPath, "background.js");
      }
      File.Delete(manifestPath);
      File.Delete(backgroundPath);
      options.AddExtension(archiveFilePath);
  }
  private static string ReplaceTemplates(string str, FiddlerOption fiddlerOption)
  {
      if (fiddlerOption.OnBeforeRequestOptions != null)
      {
          var beforeConfigs = Newtonsoft.Json.JsonConvert.SerializeObject(fiddlerOption.OnBeforeRequestOptions);
          str = str.Replace("{before_configs}", beforeConfigs);
      }
      return str;
  }

上面的代码主要是创建一个chrome扩展zip包

  然后再selenium.chrome启动的时候传进去这个zip包的地址

  使用方法

python 复制代码
var driverBinary = @"D:\soft\chrome\chrome2\Chrome-bin\";
  ChromeOptions options = new ChromeOptions
  {
      BinaryLocation = Path.Combine(driverBinary, "chrome.exe")
  };
  Environment.SetEnvironmentVariable("webdriver.chrome.driver", driverBinary);
  options.AddArgument("--disable-blink-features=AutomationControlled");
  options.AddArguments("--disable-infobars");
  List<string> ls = new List<string> { "enable-automation" };
  options.AddExcludedArguments(ls);
  #region Fillder
  options.AddFiddler(new FiddlerOption
  {
      OnBeforeRequestOptions = new List<FiddlerOnBeforeRequestOptions>
      {
          // 配置转发
          new FiddlerOnBeforeRequestOptions
          {
              Match = "https://www.cnblogs.com/yudongdong/ajax/GetPostStat",//正则
              RedirectUrl = "http://localhost:5000/GetPostStat",//如果匹配成功则将requestBody转发到这个url中去
              Cancel = false//如果配置了cancel=true那么转发将无效,true的意思是直接拦截这次的请求,不去发送了
          },
          // 配置拦截
          new FiddlerOnBeforeRequestOptions
          {
              Match = "https://www.cnblogs.com/yudongdong/ajax/blogStats",
              Cancel = true//true的意思是直接拦截这次的请求,不去发送了
          },
      }
  });
  #endregion
  var chrome = new ChromeDriver(driverBinary, options);

实现效果

最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:

这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!

相关推荐
Raink老师7 小时前
【AI面试临阵磨枪-79】实时数据 RAG:订单、商家、物流、天气、动态库存
人工智能·面试·职场和发展
Cosolar7 小时前
Chroma向量库面试学习指南
数据库·人工智能·面试·职场和发展·数据库架构
秦明月1312 小时前
电芯装配测试线安全回路设计实战
经验分享·其他·职场和发展·创业创新·学习方法
程序员小远14 小时前
系统性能指标全解析
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·性能测试
@我们的天空14 小时前
Claude Code + GLM-5 深度赋能测试:开发 8 大 Skill 构建 AI 测试助手集群
人工智能·python·测试工具·自动化·ai编程
如竟没有火炬15 小时前
乘法表中第K小的数——二分
开发语言·数据结构·python·算法·leetcode·职场和发展·动态规划
凯瑟琳.奥古斯特15 小时前
选择题专练数据库原理精选30题
开发语言·数据库·职场和发展·数据库开发
Engineer邓祥浩16 小时前
软件设计师备考 第0章 题型分布、示例、学习路线
学习·职场和发展
x_xbx18 小时前
LeetCode:739. 每日温度
算法·leetcode·职场和发展
Starry-sky(jing)18 小时前
Hermes Agent 接入 Qwen3.7-Max 报 401?OpenCode Go 模型路由源码级排查与修复
开发语言·人工智能·chrome·golang