开发者

Monitor a webpage for a text

I have the requirement to monitor a certain webpage (https) open in my browser, keep on refreshing the page and play an alarm when a particular string appears on the webpage. Is there any 开发者_运维知识库way I can achieve this.


I think this can be done with some of the following c# code. Firstly download the webpage, then check if the downloaded webpage contains the particular string.

There are plenty of tutorials on how to play sound in c#

while(true)
{
string webpage = DownloadWebpage("https://www.example.com");
if (webpage.Contains("particular string"))
{

// play warning sound!
break; // stop checking constantly
}
System.Threading.Thread.Sleep(60*1000); // 60 seconds between checking the webpage
}

Use this function to download the webpage

public static string DownloadWebpage(string url)
{
      HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
      //WebRequestObject.UserAgent = ".NET Framework/3.5";
      webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7";
      //WebRequestObject.Referer = "http://www.aWebsite.com/";


      WebResponse response = webRequest.GetResponse();
      Stream responseStream = response.GetResponseStream();
      StreamReader reader = new StreamReader(responseStream);

      string content = reader.ReadToEnd();

       reader.Close();
       responseStream.Close();
       response.Close();
       return content;
  }


What operating system are you on? If you're on Unix, it might be better to create a cronjob for it, that way you don't have a program constantly hogging memory. This is especially true if you're going to be monitoring the website for days or even weeks.

In that case the easiest way to do it would be a shell script like the following:

# Make $DONE an environment variable
url=...
your_string=...
file=
export url, your_string, file

if [$DONE]; then
    exit(1)
fi

wget $url > $file
if [grep $your_string $file]; then
    $DONE = 1
fi

Caveat: Both my solution, and the poster's above, just does a match on the html for the string. But that doesn't guarantee that the string, if found in the html, will appear in the web page presentation. Perhaps it's stored in a JavaScript array and is only printed to the screen when the user selects a certain option... maybe it was commented out... there are all kinds of possibilities. In these cases you will have to do some smarter matching than what I or the person above have suggested.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜