2011-04-15 51 views
0

我一直試圖解析一段時間php生成的網頁(不是網站)。我嘗試通過C#中的HTMLAgility和PHP來使用xpath進行解析。起初我以爲我不是正確解析,由於不正確的值。從web腳本解析腳本更改源代碼內容?

後來,我發現實際上我正確解析它。但是在該頁面中有一個腳本正在更改加載時的值。怎麼樣,我不知道。

我是新來解析,所以這裏是根據我發生了什麼:

  1. 我下載內容的源代碼。我想分析的部分是有點像這樣:

    <b id="solved_b">0</b> 
    
  2. 頁面加載時,在源代碼中的腳本時,我解析使用XPath的值變化大於0

  3. 以外的東西,原始值,即0被解析,而不是腳本更改值。

那麼,我該如何解析更改後的值而不是原來的值呢?

我試圖解析頁面 http://felix-halim.net/uva/hunting.php?id=59756

這裏是HTMLAgility的片段:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using HtmlAgilityPack; 
namespace ParseFelix { 
    class WebParser { 
     string webUrl; 

     public WebParser(string url) { 

      webUrl = "http://felix-halim.net/uva/hunting.php?id=59756"; 

      HtmlWeb htmlWeb = new HtmlWeb(); 
      HtmlDocument htmldoc = htmlWeb.Load(webUrl); 

      var username = htmldoc.DocumentNode.SelectSingleNode("/html/body/div/h2/i"); 
      var submittedStats = htmldoc.DocumentNode.SelectSingleNode(".//*[@id=\"submissions_b\"]"); 
      string content = htmldoc.DocumentNode.InnerHtml; 
      //System.IO.File.WriteAllText("D:\\exp\\felix\\parsed.txt", content); 
      var acceptedStats = htmldoc.DocumentNode.SelectSingleNode(".//*[@id=\"solved_b\"]"); 
      Console.WriteLine("Username is {0}, you submitted {1} solutions, and {2} were accepted", username.InnerText, submittedStats.InnerText, acceptedStats.InnerText); 

      } 
    } 
} 

回答

0

那麼你要做的是解析JavaScript的權利? 這是AFAIK不可能(除了編寫自己的解析器或使用現有的解析器)。 你想要的是讀操縱的DOM,並且這根本不是微不足道的

+0

我會盡力的。感謝您的回覆:D – LordAmit 2011-04-15 05:47:37

+0

可以請您提供一些關於如何閱讀操作DOM的教程? – LordAmit 2011-04-15 07:02:05

+0

不像前面提到的那樣,你必須編寫自己的JS解析器,並連接到你不想聽的事件。 – 2011-04-15 07:29:14

0

使用Fiddler - 你會看到網站讓AJAX查詢和一些值從JSON獲得:

POST http://felix-halim.net/uva/service2.php HTTP/1.1 
Host: felix-halim.net 
User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:2.0) Gecko/20100101 Firefox/4.0 
Accept: */* 
Accept-Language: lt 
Accept-Encoding: gzip, deflate 
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 
Keep-Alive: 115 
Proxy-Connection: keep-alive 
Content-Type: application/x-www-form-urlencoded; charset=UTF-8 
X-Requested-With: XMLHttpRequest 
Referer: http://felix-halim.net/uva/hunting.php?id=59756 
Content-Length: 73 
Cookie: PHPSESSID=o6if4t4vqadv7ia6vbqcfcvi75 
Pragma: no-cache 
Cache-Control: no-cache 

{"method":"uva2.chat_update","params":[12150,59756,"guest",3127,8744317]} 

和響應:

HTTP/1.0 200 OK 
Date: Fri, 15 Apr 2011 05:32:08 GMT 
Server: Apache 
X-Powered-By: PHP/5.2.15 
Expires: Thu, 19 Nov 1981 08:52:00 GMT 
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 
Pragma: no-cache 
Vary: Accept-Encoding 
Content-Type: text/html 
Content-Length: 2069 

[null,[["0","guest","1302842169"],["0","guest","1302793161"]<SKIPPED> 
+0

順便說一句,如果你想看看你沒有javascript,不錯的工具是Firefox + Noscript + Firebug – VikciaR 2011-04-15 05:37:21

+0

啊,我猜我的猜測是或多或少正確。這是我第二天的解析。所以我需要更多地研究這個問題。謝謝你的回覆。^_^ – LordAmit 2011-04-15 05:46:34