簡體   English   中英

通過Web瀏覽器元素獲取文檔內容

[英]Get document content through web browser element

我想從特定的URL獲取內容。 我嘗試了這段代碼:

var request = (HttpWebRequest)WebRequest.Create("https://example.com");
request.Timeout = 5000;
request.Method = "GET";
request.ContentType = "text/xml";

using (var _webResponse = (HttpWebResponse)_request.GetResponse())
{
    var webResponseStatus = _webResponse.StatusCode;
    var stream = _webResponse.GetResponseStream();

    using (var _streamReader = new StreamReader(_stream))
    {
        string plainText = _streamReader.ReadToEnd();
    }
}

問題在於內容不相關,似乎返回了垃圾塊。 例如,這是我收到的內容的開頭:

<!doctype html><html itemscope=\"\"
itemtype=\"http://schema.org/WebPage\" dir=\"rtl\"><head><meta
itemprop=\"image\"
content=\"/images/google_favicon_128.png\"><title>Google</title><script>(function(){\nwindow.google={kEI:\"JVMWU4OxMuL9ygOem4GACw\",getEI:function(a){for(var
b;a&&(!a.getAttribute||!(b=a.getAttribute(\"eid\")));)a=a.parentNode;return
b||google.kEI},https:function(){return\"https:\"==window.location.protocol},kEXPI:\"17259,4000116,4007661,4007830,4008067,4008133,4008142,4009033,4009565,4009641,4010297,4010806,4010830,4010858,4010899,4011228,4011258,4011679,4012318,4012373,40125

我想獲取顯示在網頁中的文本。 我該怎么做呢 ? 感謝您的幫助。 謝謝,阿維。

那不是垃圾。 返回的文本是一堆Javascript。 在瀏覽器中加載頁面后,瀏覽器將執行Javascript,該Javascript下載一些數據並修改DOM。

如果要呈現的HTML,則可以創建WebBrowser組件以顯示頁面,然后通過該組件訪問DOM,也可以將Javascript引擎添加到C#程序中並讓它解釋網頁。 有關如何執行此操作的信息,請參見將JavaScript引擎嵌入.NET

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM