我想从一个用 Drupal 制作的网站上获取一些内容。这里的挑战是我需要先登录这个网站,然后才能访问我想要抓取的页面。有没有办法在我的 C# 代码中自动执行此登录过程,以便我可以获取安全内容?
2 回答
要访问受保护的内容,您需要存储cookie并将每个请求发送到您的服务器,从发送您的登录信息的请求开始,然后保存服务器为您提供的会话 cookie(这是您证明您你说你是谁)。
您可以使用System.Windows.Forms.WebBrowser
控制较少但开箱即用的解决方案来处理 cookie。
我首选的方法是使用System.Net.HttpWebRequest
发送和接收所有 Web 数据,然后使用HtmlAgilityPack将返回的数据解析为可以轻松读取的文档对象模型(DOM)。
开始工作的诀窍System.Net.HttpWebRequest
是,您必须创建一个长期System.Net.CookieContainer
保存的日志来跟踪您的登录信息(以及服务器希望您跟踪的其他内容)。好消息是,HttpWebRequest
如果您提供容器,它将为您处理所有这些。
每次调用都需要一个新HttpWebRequest
的,因此每次都必须将它们.CookieContainer
设置为相同的对象。这是一个例子:
未经测试
using System.Net;
public void TestConnect()
{
CookieContainer cookieJar = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.mysite.com/login.htm");
request.CookieContainer = cookieJar;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// do page parsing and request setting here
request = (HttpWebRequest)WebRequest.Create("http://www.mysite.com/submit_login.htm");
// add specific page parameters here
request.CookeContainer = cookieJar;
response = (HttpWebResponse) request.GetResponse();
request = (HttpWebRequest)WebRequest.Create("http://www.mysite.com/secured_page.htm");
request.CookeContainer = cookieJar;
// this will now work since you have saved your authentication cookies in 'cookieJar'
response = (HttpWebResponse) request.GetResponse();
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer.aspx