【问题标题】:HtmlAgilityPack and AuthenticationHtmlAgilityPack 和身份验证
【发布时间】:2014-06-11 11:42:01
【问题描述】:

如果给定一个特定的 url,我有一个方法来获取 ids 和 xpaths。如何在请求中传递用户名和密码,以便我可以抓取需要用户名和密码的 url?

using HtmlAgilityPack;

_web = new HtmlWeb();

internal Dictionary<string, string> GetidsAndXPaths(string url)
{
    var webidsAndXPaths = new Dictionary<string, string>();
    var doc = _web.Load(url);
    var nodes = doc.DocumentNode.SelectNodes("//*[@id]");
    if (nodes == null) return webidsAndXPaths;
    // code to get all the xpaths and ids

我应该使用网络请求来获取页面源,然后将该文件传递给上述方法吗?

var wc = new WebClient();
wc.Credentials = new NetworkCredential("UserName", "Password");
wc.DownloadFile("http://somewebsite.com/page.aspx", @"C:\localfile.html");

【问题讨论】:

  • 我会先粘贴您遇到的任何错误。其次,尝试使用System.Net.Http.HttpClient,因为它更清楚如何设置身份验证详细信息。

标签: c# html-agility-pack networkcredentials


【解决方案1】:

HtmlWeb.Load 有许多重载,它们要么接受 NetworkCredential 的实例,要么您可以直接传入用户名和密码。

Name // Description 
Public method Load(String) //Gets an HTML document from an Internet resource.  
Public method Load(String, String) //Loads an HTML document from an Internet resource.  
Public method Load(String, String, WebProxy, NetworkCredential) //Loads an HTML document from an Internet resource.  
Public method Load(String, String, Int32, String, String) //Loads an HTML document from an Internet resource. 

WebProxy实例不需要传入,也可以传入系统默认的。

或者,您可以连接 HtmlWeb.PreRequest 并为请求设置凭据。

htmlWeb.PreRequest += (request) => {
    request.Credentials = new NetworkCredential(...);
    return true;
};

【讨论】:

  • htmlWeb.PreRequestHandler +=应该是htmlWeb.PreRequest +=
猜你喜欢
  • 2015-02-02
  • 2018-02-24
  • 1970-01-01
  • 2015-08-10
  • 2012-10-14
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多