WebClient.DownloadString(url) 当这个url返回404页面时,我怎样才能跳过这个?

发布于 2024-12-27 20:09:53 字数 143 浏览 3 评论 0原文

我正在使用 WebClient.DownloadString(url) 下载网页,当 url 为 404 网页时,它会停止并且不再工作。 当我遇到这个错误时,我想跳过这些页面。

如果url是404页面,则不会开始下载。所以我无法解析未下载的数据......

I'm using WebClient.DownloadString(url) to download a web page, when a url a 404 web page it stops and doesn't work anymore.
I want to skip these pages when I got this fault.

if the url is 404 page, it doesn't start to download. so i can't parse the undownloaded data...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

思慕 2025-01-03 20:09:53

您必须捕获异常并测试 404:

try
{
    string myString;
    using (WebClient wc = new WebClient())
        myString= wc.DownloadString("http://foo.com");

}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
    {
        var resp = (HttpWebResponse)ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
        {
            //the page was not found, continue with next in the for loop
            continue;
        }
    }
    //throw any other exception - this should not occur
    throw;
}

You will have to catch the Exception and test for a 404:

try
{
    string myString;
    using (WebClient wc = new WebClient())
        myString= wc.DownloadString("http://foo.com");

}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
    {
        var resp = (HttpWebResponse)ex.Response;
        if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
        {
            //the page was not found, continue with next in the for loop
            continue;
        }
    }
    //throw any other exception - this should not occur
    throw;
}
暮倦 2025-01-03 20:09:53

您可以将代码放在 Try...Catch 块中并捕获 WebException.如果您想要更多地控制如何处理特定错误,可以使用 WebException 的 Status 属性,该属性返回 WebExceptionStatus 枚举。

You can put your code in a Try...Catch block and catch a WebException. If you want more control on how to handle specific errors, you can use the WebException's Status property which returns a WebExceptionStatus enumeration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文