繁体   English   中英

获取登录表单保护的Drupal网站的内容

[英]Grab the contents of a Drupal website that is secured with a login form

我想从Drupal制作的网站上获取一些内容。 这里的挑战是,我需要先登录此网站才能访问要抓取的页面。 有没有一种方法可以在我的C#代码中自动执行此登录过程,以便获取安全内容?

您必须使用“ 服务”模块来执行此操作。 另请查看链接以获取一些说明。

要访问受保护的内容,您需要将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/zh-CN/library/system.windows.forms.webbrowser.aspx

HttpWebRequest类别

http://msdn.microsoft.com/zh-CN/library/system.net.httpwebrequest.cookiecontainer.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM