识别硒C#中的有效链接和无效链接

时间:2018-12-03 14:28:15

标签: c# selenium logging

我登录到网站->我从文本文件中读取链接(其中有有效的链接和损坏的链接)->我正在使用HttpWebRequest和HttpWebResponse来检测有效和无效的链接---这是主要的问题--->我正在尝试分离工作链接和不工作链接,并登录到两个不同的文件中。但是所有内容都只放入一个文件中。我正在使用StatusCode属性来区分两者。但是没有成功。请在下面找到代码。我是硒C#的新手。

public void Login()
    {
        WebDriver.Navigate().GoToUrl($"{ApplicationUrl}Login.aspx");
        WebDriver.Manage().Window.Maximize();
        WebDriver.FindElement(By.Id("UserName")).SendKeys(_user.Login);
        WebDriver.FindElement(By.Id("tbPassword")).SendKeys(_user.Passwort);
        IJavaScriptExecutor js = WebDriver as IJavaScriptExecutor; 
        js.ExecuteScript("arguments[0].click();", 
        WebDriver.FindElement(By.Id("LoginButton")));
        Thread.Sleep(3000);

        string fileName = @"TestFile.txt";
        // Reading the text file using StreamReader
        using (StreamReader sr = new StreamReader(fileName))
        {
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                WebDriver.Navigate().GoToUrl(line);
                IsLinkWorking(line);
            }
            WorkingLinks.Close();
            NotWorkingLinks.Close();
        }
    } 


    public void IsLinkWorking(string line)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(line);
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                WorkingLinks.WriteLine(WebDriver.Url);
                // Releases the resources of the response.
                response.Close();
            }
            else
            {
                NotWorkingLinks.WriteLine(WebDriver.Url);
                response.Close();
            }
        }
        catch
        { //TODO: Check for the right exception here
        }
    }

1 个答案:

答案 0 :(得分:0)

当HTTP状态代码超出200-299范围时,它将发送到catch中,在此处设置代码

catch
{ 
    NotWorkingLinks.WriteLine(WebDriver.Url);
}