在我想要的项目中,我希望能够查看一个网站,从该网站检索文本,并稍后使用该信息执行某些操作。
我的问题是从网站检索数据(文本)的最佳方式是什么。我不确定在处理静态页面与处理动态页面时如何执行此操作。
通过一些搜索我发现了这个:
WebRequest request = WebRequest.Create("anysite.com");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
Console.WriteLine();
// Get the stream containing content returned by the server.
using (Stream dataStream = response.GetResponseStream())
{
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream, Encoding.UTF8);
// Read the content.
string responseString = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseString);
reader.Close();
}
response.Close();
因此,通过我自己运行它,我可以看到它从网站返回 html 代码,而不是我正在寻找的内容。我最终希望能够输入一个网站(例如一篇新闻文章),并返回文章的内容。这在 C# 或 Java 中可能吗?
谢谢
最佳答案
我不想告诉你,但这就是网页的样子,它是一长串 html 标记/内容。浏览器将其呈现为您在屏幕上看到的内容。我能想到的唯一办法就是自己解析成html。
在谷歌上快速搜索后,我发现了这篇堆栈溢出文章。 What is the best way to parse html in C#?
但我敢打赌您认为这会比您预期的要容易一些,但这就是编程中总是具有挑战性的问题的乐趣
关于c# - 从网站读取信息c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231002/