【问题标题】:Client stuck downloading website source c#客户端卡住下载网站源c#
【发布时间】:2021-02-19 20:59:55
【问题描述】:

我正在尝试下载一个网站源代码,一按按钮开始检索,程序就会无限卡住

我的代码:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (WebClient client = new WebClient())
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                string html = client.DownloadString("https://www.finanzen.net/termine/unternehmen/");
                MessageBox.Show(html);
            }
        }
    }
}

我该如何解决这个问题?任何帮助表示赞赏:)

【问题讨论】:

  • 您可以在 Visual Studio 中设置断点并查看导致此行为的原因。
  • WebClient 已经过时了,你应该改用HttpClient

标签: c# html web-scraping webclient


【解决方案1】:

我更喜欢使用方法的异步实现。请看下面的例子:

private async void button1_Click(object sender, EventArgs e)
        {
            using (WebClient client = new WebClient())
            {
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
                string html = await client.DownloadStringAsync("https://www.finanzen.net/termine/unternehmen/");
                MessageBox.Show(html);
            }
        }

编辑: 我建议您在 GUI 中添加一个 DataGrid,而不是在 MessageBox 中显示结果。结果将存储在列表中,然后显示在 GUI 上。

【讨论】:

  • 我们在这里不回答我们“喜欢”的内容。这也不会编译,因为事件处理程序必须返回 voidTask 无效)
  • 您不能等待DownloadStringAsync,该方法是事件驱动的,它不会返回可等待的任务。异步的、等待的、版本DownloadStringTaskAsync
【解决方案2】:

你对穷人MessageBox.Show的要求太高了。 html423,467 字符长。试试这个:

MessageBox.Show(html.Substring(0, Math.Min(html.Length, 1000)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    相关资源
    最近更新 更多