10

I have a method to get ids and xpaths if given a particular url. How do I pass in the username and password with the request so that I can scrape a url that requires a username and password?

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

Should I use a web request to get the page source and then pass that file into the method above?

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

1 回答 1

5

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;
};
于 2014-04-26T07:49:56.717 回答