在我的项目中,我希望能够查看一个网站,从该网站检索文本,并在以后使用该信息进行某些操作。

我的问题是从网站检索数据(文本)的最佳方法是什么。我不确定在处理静态页面与处理动态页面时该如何做。

通过一些搜索,我发现了这一点:

        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。

在Google上快速搜索后,我发现了此堆栈溢出文章。
What is the best way to parse html in C#?

但是我敢打赌,您认为这样做会比您预期的要容易一些,但这是编程中总是有挑战性的问题的乐趣

10-07 18:59
查看更多