C# - How to detect if website return page with con

2019-09-12 09:01发布

I have a project about going to a website. If the website cannot be loaded, and the browser will show a page with text: "This page cannot be displayed" .In this situation, I want to auto refresh the browser. How will the program detect that website can't be loaded? . I've tried Ping() to check the connection, but it seems the connection is fine. Take a look at my below code:

public void exam()
        {
            var ie = new IE();
            ie.GoTo("http://search.yahoo.com");
            ie.WaitForComplete(5);            
            if (ie.ContainsText("This page cannot be displayed"))
            {
                ie.Close();// or ie.Refresh()
            }

        }  

It doesn't work. Help!

标签: c# watin
2条回答
Bombasti
2楼-- · 2019-09-12 09:33

I don't know what your IE type is but you could use HttpWebRequest/HttpWebResponse and check the StatusCode property of the response.

For example: -

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.NotFound)
{
    //page not found
}
//etc....

The HttpStatusCode enum can be useful for checking against a variety of different states.

查看更多
祖国的老花朵
3楼-- · 2019-09-12 09:53

You code looks fine just remove the time from your wait for complete Make sure the text is same as displayed in the browser.

public void exam()
    {
        var ie = new IE();
        ie.GoTo("http://search.yahoo.com");
        ie.WaitForComplete();            
        if (ie.ContainsText("This page cannot be displayed"))
        {
            ie.Refresh();
        }

    }
查看更多
登录 后发表回答