我對檢查網站內容感興趣,內容經常更改,當我在任何瀏覽器上查看網站時,它每隔30秒刷新一次。我想知道內容何時發生變化。c#WebBrowser DocumentText工作但不在循環中?
我正在使用winforms,我只想點擊一個按鈕來啓動一個循環,每30秒。我不想過於頻繁地訪問網站,實際上網頁自己的刷新已經足夠滿足我的需求。
當我點擊一個按鈕(btnCheckWebsite)時,我的代碼有效,如果我等一會兒,然後再次點擊btnCheckWebsite,我的消息框會彈出,因爲網頁已更改。這是偉大的,但我想在一個while循環中做到這一點。當我對while循環取消註釋時,DocumentText從不改變。我已經對它進行了調試,出於某種原因,每次都是相同的文本,即使網頁在真實世界中發生了變化,它在我的代碼中也保持不變。
所以我的問題是爲什麼我不能使用一個循環,我可以做什麼來反覆運行,沒有任何來自我的輸入?
作爲獎勵,我想刪除.Refresh()我添加了這個,因爲它不會沒有它的工作,但據我瞭解,這刷新了整個頁面。當我使用瀏覽器時,即使不刷新整個頁面,我也會看到頁面更新。
只是爲了背景信息,我確實通過在窗體上使用WebBrowser控件開始,頁面自動刷新。我使用相同的代碼,並有相同的問題,有趣的是,我的Windows窗體上的WebBrowser控件本身刷新沒有問題,直到我點擊btnCheckWebsite,然後停止刷新!我也瞭解webrequest,但我不知道如何將其用於我的目的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Check_Website
{
public partial class Form1 : Form
{
public WebBrowser _memoryWebBrowser = new WebBrowser();
String _previousSource = "emptySource";
public Form1()
{
InitializeComponent();
_memoryWebBrowser.Navigate(new Uri("http://www.randomurl.com/"));
}
private void btnCheckWebsite_Click(object sender, EventArgs e)
{
//I want to un-comment this while loop and let my code run itself but it stops working
//when I introduce my while loop.
//while (1 < 2)
//{
//Thread.Sleep(30000);
checkWebsite();
//}
}
private void checkWebsite()
{
//Why do I need this refresh? I would rather not have to hit the web page with a refresh.
//When I view the webpage it refreshed with new data however when I use a WebBrowser
//the refresh just doesn't happen unless I call Refresh.
_memoryWebBrowser.Refresh();
Thread.Sleep(500);
while (((_memoryWebBrowser.ReadyState != WebBrowserReadyState.Complete) || (_memoryWebBrowser.DocumentText.Length < 3000)))
{
Thread.Sleep(1000);
}
String source = _memoryWebBrowser.DocumentText;
if ((source != _previousSource) && (_previousSource != "emptySource"))
{
//Hey take a look at the interesting new stuff on this web page!!
MessageBox.Show("Great news, there's new stuff on this web page www.randomurl.co.uk!!");
}
_previousSource = source;
}
}
}
說明您的頁面是否使用AJAX或DHTML動態更新自己,並且您想跟蹤這些更改。 – Noseratio
** [更新] **我們澄清了頁面確實動態更新了自己,解決方案是使用'Document.Document.Body.OuterHtml'來跟蹤更新。 – Noseratio