C# 正则表达式:从 Web 性能和负载测试项目中的 HTTP 响应中获取随机 URL

C# Regex: Get random URL from HTTP response in Web Perfomance and Load Test Project

你能帮我解决这个问题吗?

我有网络请求

 WebTestRequest request1 = new WebTestRequest("http://www.theverge.com/");
        request1.ParseDependentRequests = false;
        yield return request1;

及其上的回复:

      <li><a href="https://www.facebook.com/verge" tabindex="2">
        <svg class="p-svg-icon"><use xlink:href="#icon-facebook"></use></svg>
      </a></li>

      <li><a href="https://twitter.com/verge" tabindex="3">
        <svg class="p-svg-icon"><use xlink:href="#icon-twitter"></use></svg>
      </a></li>

      <li><a href="/rss/index.xml" tabindex="4">
        <svg class="p-svg-icon"><use xlink:href="#icon-rss"></use></svg>
      </a></li>

我想找到此页面上的所有 URL,并在下一步中随机使用它们。 据我了解,我应该使用

string response = LastResponse.BodyString;

比正则表达式,制作一个 ArrayList Class 并随机取一个 url.

有人可以帮我吗?

我用过的主要有两种方式。首先使用正则表达式并获取所有匹配项。 创建匹配所有需要的 URL 但不匹配不需要的 URL 的正则表达式。 我测试的一个网站有许多 URL,其中 href= 前面有一个 class=,具有多个数字级别。我只想要第 2 级和第 3 级,导致下面代码中的表达式。

当您确信 HTML 将在测试开发和测试执行的整个持续时间内采用固定格式时,这种方法就会起作用。如果 href= 的(或附近)的 HTML 可能会发生变化,那么您需要更复杂的正则表达式或其他方法。

我使用了 GetARandomNumber 方法,因为 .NET 随机数生成器不是线程安全的。例如,参见 here

public class GetAUrl : WebTestRequestPlugin
{
    public string ContextParameter { get; set; }

    public override void PostRequest(object sender, PostRequestEventArgs e)
    {
        string body = e.Response.BodyString;

        // Looking for requests in a specific class.

        string pattern = "\bclass=\"nav__link-[23]\" +href=\"(/[^\"]*)\"";
        // The URL is in this capture:                        ^^^^^^^^^

        MatchCollection matches = Regex.Matches(body, pattern);

        int randomIndex = GetARandomNumber(matches.Count);
        //  Above will get a value 0 <= randomIndex < matches.Count

        e.WebTest.Context[ContextParameter] = matches[randomIndex].Groups[1].Value;
    }
}

另一种方法使用了HtmlAgilityPack,其中方法的本质使用:

HtmlAgilityPack.HtmlNodeCollection nodes = input_doc.DocumentNode.SelectNodes("//a");

然后筛选节点集合以 select 感兴趣的节点,然后随机选择一个。

结果:

string response = LastResponse.BodyString;
            string pattern = @"regexp";

            MatchCollection results = Regex.Matches(response, pattern);
            Random rnd = new Random();
            string randomUrl = results[rnd.Next(results.Count)].Groups[1].Value;