C#獲取執行完JS之后的HTML頁面內容的代碼【草稿,有待考證】


 

爬蟲如何獲取執行完js后的html源文件,比如頁面我點擊查詢之后,自動生成一個表格承載數據 ,但是我右鍵查看源文件,是無法查看到這個JS生成的Table的。
用火狐Debug是可以的 參考網址

 

http://www.hfepb.gov.cn/kqzt.aspx

 

可以看到生成的表格。但是查看源文件,無法查看到數字。

 

網上的【------解決方案--------
通過設置webBrowser的url,把獲取到的源碼給webBrowser.Document,等webBrowser.DocumentCompleted后,獲取ebBrowser.Document應該就OK了。】

 

 

 通過嘗試按F12后,菜單【緩存】——【清除此域的...】,發現問題解決了,可以得到js執行后的完整html數據。下次執行前,還必須手動【清除】,不然還是得不到js后數據。於是,找到突破口,用代碼清除緩存,問題迎刃而解。

這個問題困擾了兩天,終於找到了解決辦法:

 

/// <summary>
        /// 針對js頁面,獲取頁面內容。火狐的“查看元素”也可以獲取。
        /// </summary>
        private void PrintHelpPage()
        {
            // Create a WebBrowser instance. 
            WebBrowser webBrowserForPrinting = new WebBrowser();

            // Add an event handler that prints the document after it loads.
            webBrowserForPrinting.DocumentCompleted +=
                new WebBrowserDocumentCompletedEventHandler(PrintDocument);
//刪除緩存為關鍵一步,必須進行;不然得不到js執行后的數據 string cachePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);//獲取緩存路徑 DirectoryInfo di = new DirectoryInfo(cachePath); foreach (FileInfo fi in di.GetFiles("*.*", SearchOption.AllDirectories))//遍歷所有的文件夾 刪除里面的文件 { try { fi.Delete(); } catch { } } // Set the Url property to load the document. webBrowserForPrinting.Url = new Uri("http://218.23.98.205:8080/aqi/components/aqi/explainDay.jsp"); } private void PrintDocument(object sender, WebBrowserDocumentCompletedEventArgs e) { //MessageBox.Show("000"); //foreach (HtmlElement he in ((WebBrowser)sender).Document.GetElementById("sljaqi")) //{ // //if (he.GetAttribute("classname") == "co_yl") // //{ // // //然后網頁信息格式,來分解出你要的信息。 // //} // MessageBox.Show(he.OuterText); // MessageBox.Show(he.Name); //} MessageBox.Show(((WebBrowser)sender).Document.GetElementById("sljaqi").InnerHtml); // Print the document now that it is fully loaded. //((WebBrowser)sender).Print(); // Dispose the WebBrowser now that the task is complete. ((WebBrowser)sender).Dispose(); }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM