如何使用Selenium C#查找Webiste的断开链接

时间:2018-12-02 11:55:45

标签: c# selenium

我对Selenium C#非常陌生。我正在寻找使用Selenium C#查找网站断开链接的方法。我可以找到一些针对Java Selenium的解决方案,但找不到使用Selenium C#的解决方案。如果有人可以为同一文档或任何文档的链接发布一小段代码,以供我参考和遵循,那将非常有帮助。提前致谢。

2 个答案:

答案 0 :(得分:4)

您可以尝试遍历“ a”标签列表,并在http请求中检查200 OK:

    IList<IWebElement> links = driver.FindElements(By.TagName("a")); 
    foreach (IWebElement link in links)
    {
      var url = link.getAttribute("href");
      IsLinkWorking(url);
    }


    bool IsLinkWorking(string url) {
       HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);

       //You can set some parameters in the "request" object...
       request.AllowAutoRedirect = true;

       try {
          HttpWebResponse response = (HttpWebResponse) request.GetResponse();
          if (response.StatusCode == HttpStatusCode.OK)
          {
            Console.WriteLine("\r\nResponse Status Code is OK and 
            StatusDescription is: {0}", response.StatusDescription);
            // Releases the resources of the response.
            response.Close(); 
            return true;
          }
          else
          {
            return false;
          }
       } catch { //TODO: Check for the right exception here
          return false;
       }
     }

答案 1 :(得分:0)

IWebDriver webDriver = new ChromeDriver();
webDriver.Navigate().GoToUrl("https://www.google.co.in/maps/");
HttpWebRequest req = null;
var urls = Driver.FindElements(By.TagName("a"));

foreach (var url in urls)
{
     if (!(url.Text.Contains("Email") || url.Text == ""))
     {
            req = (HttpWebRequest)WebRequest.Create(url.GetAttribute("href"));
           try
           {
                var response = (HttpWebResponse)re.GetResponse();
                System.Console.WriteLine($"URL: {url.GetAttribute("href")} status is :{response.StatusCode}");
            }
            catch (WebException e)
            {
                  var errorResponse = (HttpWebResponse)e.Response;
                  System.Console.WriteLine($"URL: {url.GetAttribute("href")} status is :{errorResponse.StatusCode}");
              }
      }
}