![](/img/trans.png)
[英]On a web page with Html Table, how do I determine if a Html Row is selected or not using c#?
[英]how do I use C# to dump a web page's HTML to a text file?
我正在做一個項目,在這個項目中,我需要能夠以網站網址www.google.com
為例,並在單獨解析的文本文件中獲取它的html,但我不知道該怎么做。
我知道有一種比我做起來更容易的方法,但這是一個旨在利用和增加知識的項目。
使用WebClient
僅將單個URL下載到文件非常簡單:
using (var client = new WebClient())
{
client.DownloadFile(url, filename);
}
棘手的一點是,很少有真正由單個HTML組成的網頁-大多數網頁然后加載Javascript,或使用 Javascript加載更多數據,等等。
在.NET 4.5和以后你可能想使用HttpClient
,而不是WebClient
-雖然這是異步的,(據我可以看到)不提供任何比較一樣便利DownloadFile
當這一切你想做的事。
您可以嘗試HtmlAgilityPack:
string Url = "http://something";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
string contents= doc.DocumentNode.OuterHtml;
File.WriteAllText("X:\abc\def.txt", contents);
C#WebClient類可以幫助您實現這一目標:
using System;
using System.Net;
using System.IO;
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString("http://somesite.com/default.html");
File.WriteAllText(@"c:\YourLocalFolder\somefile.txt", htmlCode);
}
如果還有其他所有文件,則可以使用WebBrowser控件在應用程序中運行IE,這可以運行頁面上的jscript等。然后,您可以從C#訪問DOM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.