【问题标题】:How to check if it is 404 error page and do something using HtmlAgilityPack如何检查它是否是 404 错误页面并使用 HtmlAgilityPack 执行某些操作
【发布时间】:2019-05-18 19:27:03
【问题描述】:

我正在尝试使用 HtmlAgilityPack 从不同的 url 获取多个数据。

  • 它将获得产品价格。
  • 但是当产品库存为 0 时。他们正在关闭页面。

我的程序将价格添加到列表框。当页面给出 404 它应该添加空列表框项。

有没有办法让程序更简单?我不能在同一个按钮上使用相同的变量。我正在添加相同的代码来更改数字 (6)。

WebRequest SiteyeBaglantiTalebi06 = HttpWebRequest.Create("https://www.themia.com.tr/The-Mia-Dekor-Mermer-22-Cm-Gri,PR-2432.html");
WebResponse GelenCevap06 = SiteyeBaglantiTalebi06.GetResponse();
StreamReader CevapOku06 = new StreamReader(GelenCevap06.GetResponseStream());

string KaynakKodlar06 = CevapOku06.ReadToEnd();
int IcerikBaslangicIndex06 = KaynakKodlar06.IndexOf("<div class=\"productPrice\">") + 122;
int IcerikBitisIndex06 = KaynakKodlar06.Substring(IcerikBaslangicIndex06).IndexOf("</div>");

listBox3.Items.Add((KaynakKodlar06.Substring(IcerikBaslangicIndex06, IcerikBitisIndex06)));

【问题讨论】:

  • 代码格式化,基本文本编辑

标签: c# html-agility-pack


【解决方案1】:

如果您将WebResponse 转换为HttpWeResponse,您可以访问StatusCode 属性-https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.statuscode?view=netframework-4.7.2#System_Net_HttpWebResponse_StatusCode

只需要注意一件事 - 当 HttpWebRequest 收到不表示成功的状态代码时,您不能让 HttpWebRequest 不抛出异常(更有理由不使用此方法)。这意味着您必须准备好捕获将被抛出的异常。

所以在你的例子中,它会是 -

WebRequest SiteyeBaglantiTalebi06 = HttpWebRequest.Create("https://www.somesite.com/NotARealPath");
try
{
    WebResponse GelenCevap06 = SiteyeBaglantiTalebi06.GetResponse();
    // do things with the result
}
catch (WebException ex)
{
    using (WebResponse response = ex.Response)
    {
        HttpWebResponse asHttp = (HttpWebResponse)response;
        if (asHttp.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            // your 404 logic here
        }
        else 
        {
            // your "something went wrong but it's not a 404" logic 
        }
    }
}

至于使代码更简单 - 如果不了解更多关于您的程序和您正在尝试做什么,就很难准确理解您的意思。总的来说,这里有一些想法 -

【讨论】:

  • 我仍然收到此错误:System.Net.WebException:'远程服务器返回错误:(404)未找到。'
  • 你是对的 - 我忘记了这种行为(抛出异常)不能被关闭(有关另一个相关问题,请参阅here)。我编辑了答案以显示如何处理这个问题(但我仍然建议不要使用 API,有更好的选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2015-06-25
  • 2012-07-12
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多