问题
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