C# - How to detect if website return page with content “This page cannot be displayed ”using Watin?

ⅰ亾dé卋堺 提交于 2019-12-13 04:30:43

问题


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!


回答1:


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.




回答2:


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();
        }

    }


来源:https://stackoverflow.com/questions/17553320/c-sharp-how-to-detect-if-website-return-page-with-content-this-page-cannot-be

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!