使用HtmlAgilityPack搜寻网址内容会产生错误

时间:2018-09-12 06:21:23

标签: c# asp.net webforms html-agility-pack

我正在使用HtmlAgilityPack从url抓取文本,该文本对于大多数网站都适用,并且对于某些网站而言今天开始返回错误。

错误跟随行代码doc = webGet.Load(url); 错误消息:The underlying connection was closed: An unexpected error occurred on a send.

不知道为什么我会收到此错误,因为它以前与此网站的网址一起使用 范例网址:link

我尝试了诸如bbc.com之类的https url,它可以工作。任何指针,如果他们的代码有问题

 HtmlDocument doc = new HtmlDocument();
            var url = txtGrabNewsURL.Text.Trim();

        var webGet = new HtmlWeb();
        doc = webGet.Load(url);
        var baseUrl = new Uri(url);
        //  doc.LoadHtml(response);

        String title = (from x in doc.DocumentNode.Descendants()
                        where x.Name.ToLower() == "title"
                        select x.InnerText).FirstOrDefault();

        String desc = (from x in doc.DocumentNode.Descendants()
                       where x.Name.ToLower() == "meta"
                       && x.Attributes["name"] != null
                       && x.Attributes["name"].Value.ToLower() == "description"
                       select x.Attributes["content"].Value).FirstOrDefault();

        String ogImage = (from x in doc.DocumentNode.Descendants()
                          where x.Name.ToLower() == "meta"
                          && x.Attributes["property"] != null
                          && x.Attributes["property"].Value.ToLower() == "og:image"
                          select x.Attributes["content"].Value).FirstOrDefault();


        List<String> imgs = (from x in doc.DocumentNode.Descendants()
                             where x.Name.ToLower() == "img"
                              && x.Attributes["src"] != null
                             select x.Attributes["src"].Value).ToList<String>();

        List<String> imgList = (from x in doc.DocumentNode.Descendants("img")
                                where x.Attributes["src"] != null
                                select x.Attributes["src"].Value.ToLower()).ToList<String>();

完整错误详细信息

System.Net.WebException was caught
  HResult=-2146233079
  Message=The underlying connection was closed: An unexpected error occurred on a send.
  Source=System
  StackTrace:
       at System.Net.HttpWebRequest.GetResponse()
       at HtmlAgilityPack.HtmlWeb.Get(Uri uri, String method, String path, HtmlDocument doc, IWebProxy proxy, ICredentials creds) in D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1355
       at HtmlAgilityPack.HtmlWeb.LoadUrl(Uri uri, String method, WebProxy proxy, NetworkCredential creds) in D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1479
       at HtmlAgilityPack.HtmlWeb.Load(String url, String method) in D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1106
       at HtmlAgilityPack.HtmlWeb.Load(String url) in D:\Source\htmlagilitypack.new\Trunk\HtmlAgilityPack\HtmlWeb.cs:line 1061
       at _admin_News.btnGrabNews_Click(Object sender, EventArgs e) in c:\path\News.aspx.cs:line 361
  InnerException: System.IO.IOException
       HResult=-2146232800
       Message=Authentication failed because the remote party has closed the transport stream.
       Source=System
       StackTrace:
            at System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
            at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
            at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
            at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
            at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
            at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
            at System.Net.TlsStream.CallProcessAuthentication(Object state)
            at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
            at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
            at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
            at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
            at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
            at System.Net.ConnectStream.WriteHeaders(Boolean async)
       InnerException: 

2 个答案:

答案 0 :(得分:3)

如果仅使用HTTP S 资源发生这种情况,则您的目标是.Net 4,那么它可能与默认的SSL / TLS支持有关。请尝试以下操作:

using System.Net;

static void Main()
{
    //place this anywhere in your code prior to invoking the Web request
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 |  SecurityProtocolType.Ssl3; 
}

答案 1 :(得分:0)

我在本地计算机上运行了代码,它运行正常,并且得到了输出而没有任何错误。 我以为网站无法正常工作,出现连接问题。

   HtmlDocument doc = new HtmlDocument();
        var url = "https://m.gulfnews.com/business/sectors/banking/rebuilding-lives-10-years-after-lehman-s-fall-1.2277318"

    var webGet = new HtmlWeb();
    doc = webGet.Load(url);

    String title = (from x in doc.DocumentNode.Descendants()
                    where x.Name.ToLower() == "title"
                    select x.InnerText).FirstOrDefault();

输出:重建生活,10。 。 。 。 。等等。