如何获取网页的 txt 内容
本文关键字:网页 txt 内容 获取 何获取 | 更新日期: 2023-09-27 18:36:07
我浪费了 2 天时间来发现,WebBrowser 控件中存在已知的内存泄漏(自 2007 年左右以来,他们仍然没有修复它),所以我决定在这里简单地问一下,如何做我需要的事情。
到目前为止,(使用WebBrowser...),我一直在访问一个网站,(ctrl + a),将其粘贴到字符串中,仅此而已。我的字符串中有网页的文本内容。完美运行,直到我发现一段时间后它需要 1 GB 的内存。是否有可能通过HttpWebRequest,httpwebclient或其他任何东西来做到这一点?
感谢您的回复,没有任何这样的线程(或者我没有找到任何线程,搜索并没有真正花费我太多时间,因为我现在真的很生气:P)
忘了添加:我不想要HTML代码,我知道可以轻松获得它。就我而言,html代码是无用的。我确实需要用户在使用互联网浏览器打开页面时看到的文本。
using (WebClient client = new WebClient())
{
string html = client.DownloadString("http://stackoverflow.com/questions/10839877/how-to-get-a-txt-content-of-a-web-page");
}
这将从任何网页下载 html 内容。
WebClient client = new WebClient ();
string reply = client.DownloadString ("http://www.google.com");
你可以使用这个:
string getHtml(string url) {
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader source = new StreamReader(myWebResponse.GetResponseStream());
string pageSourceStr = string.Empty;
pageSourceStr= source.ReadToEnd();
response.Close();
return pageSourceStr;
}
您仍然需要执行一些子字符串替换以将其从html减少为文本。如果您只想从某个div获得文本,那还不错。
为什么不使用像Ncrawler这样的免费开源HTML抓取工具。
它是用 c# 编写的。
ncrawler.codeplex.com
您可以在此处获取有关如何使用它的示例。