【问题标题】:Use a web page as an input for a C# project [closed]使用网页作为 C# 项目的输入[关闭]
【发布时间】:2013-01-07 09:54:54
【问题描述】:

如何在网页内容 (html) 中扫描(如 scanf(来自 C)和 Scanner 类(来自 Java))并将其用作我的程序的输入?

string[] line = new string[length];
for (int i = 0; i < line.Length; i++) {
  line[i] = Console.ReadLine();
  //Can I have ReadLine read from a website not the Console?
}

例如我想在 Web 服务器上放置一个包含我附近公共汽车时刻表的文本文件,然后访问它并使用它为我的应用程序生成输出。这样我就可以更新它并且始终可以访问这些更新。

附:我是一名初级程序员,尤其是一名初级 C# 程序员,所以我很难找到我正在寻找的内容,因为我不知道要搜索什么。

感谢您的帮助:我能够开始寻找正确的东西,这很有效:

class MainClass
{
    public static void Main (string[] args)
    {
        // Create web client.
        WebClient client = new WebClient();

        // Download string.
        string value = client.DownloadString("http://www.example.com");

        // Write values.
        Console.WriteLine("--- WebClient result ---");
        Console.WriteLine(value.Length);
        Console.WriteLine(value);
    }
}

【问题讨论】:

  • 搜索词:“网页抓取”和“C# WebClient 下载”。请进行研究,然后使用示例代码提出具体问题。

标签: c# html web


【解决方案1】:
private void Test()
{
    string pageData = DownloadWebPage(new Uri("http://www.yourftp.com"));
    //parse data
}

private string DownloadWebPage(Uri path)
{
    string webPageData = null;

    using (WebClient client = new WebClient())
    {
        client.DownloadStringAsync(path);
        client.DownloadStringCompleted += (sender, args) => webPageData = args.Result;
    }

    return webPageData;
}

上传后,您可以使用上述方法从您的网络服务器下载文本文件。只需将 URI 传递给 DownloadWebPage 方法,它就会返回文本页面。如果您需要帮助解析文本文档以提供有意义的 C# 表示,您需要给出文本文件的示例并描述您希望如何解析它。

【讨论】:

  • 谢谢!我能够搜索 WebClient 并找到我需要的东西。
【解决方案2】:

您可以通过 URL 请求内容,然后使用 HTML Agility Pack 之类的工具将其加载到 HTML 文档中。请参阅此 SO 线程以获取建议 What is the best way to parse html in C#?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多