Selenium WebDriver 是一組開源 API,用於自動測試 Web 應用程式,利用它可以通過程式碼來控制chrome瀏覽器!
有時候我們需要mock介面的返回,或者攔截和轉發請求,今天就來實現這個功能
程式碼已開源: https://github.com/yuzd/OpenQA.Selenium.Chrome.Fiddler
OpenQA.Selenium.Chrome.Fiddler
我們新建立一個功能:OpenQA.Selenium.Chrome.Fiddler
一個chrome擴充套件 最起碼有2個檔案
稍微解釋一下:
{
"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"
}
因為攔截api 或者 轉發 需要用的chrome的api
chrome.webRequest.onBeforeRequest.addListener(
function(details) {
//邏輯處理
},
{ urls: ['<all_urls>']},
['blocking', 'extraHeaders', 'requestBody']
);
這個api的函數 接收的details引數
函數的返回
新建一個netstand工程,然後參照
複製以下程式碼
/// <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包的地址
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);