22

我需要来自不属于我的网站的一些信息,为了获取这些信息,我需要登录该网站以收集信息,这通过 HTML 表单进行。如何在 C# 中进行此经过身份验证的屏幕截图?

额外的信息:

  • 基于 Cookie 的身份验证。
  • 需要 POST 操作。
4

5 回答 5

24

您会像刚刚填写表格一样提出请求。例如,假设它是 POST,您使用正确的数据发出 POST 请求。现在,如果您无法直接登录到要抓取的同一页面,则必须跟踪登录请求后设置的任何 cookie,并将它们包含在您的抓取请求中以允许您保持登录状态。

它可能看起来像:

HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData="FormNameForUserId=" + strUserId + "&FormNameForPassword=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
    postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;

也许。

于 2009-06-10T13:11:53.297 回答
6

您可以使用WebBrowser控件。只需将站点的 URL 输入它,然后使用 DOM 将用户名和密码设置到正确的字段中,最后发送一个点击到提交按钮。这样,除了两个输入字段和提交按钮之外,您什么都不关心。没有 cookie 处理,没有原始 HTML 解析,没有 HTTP 嗅探——所有这些都由浏览器控件完成。

如果你这样做,还有一些建议:

  1. 您可以阻止控件加载诸如 Flash 之类的加载项 - 可以为您节省一些时间。
  2. 登录后,您可以从 DOM 获取所需的任何信息 - 无需解析原始 HTML。
  3. 如果您想让该工具在站点将来发生变化时更加便携,您可以使用 JavaScript 注入替换显式 DOM 操作。JS可以从外部资源中获取,调用后可以进行字段填充和提交。
于 2009-06-10T13:44:13.933 回答
3

在某些情况下,httpResponse.Cookies将为空白。改为使用CookieContainer

CookieContainer cc = new CookieContainer();

HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";

http.CookieContainer = cc;

string postData="FormNameForUserId=" + strUserId + "&FormNameForPassword=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
    postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;

http.CookieContainer = cc;

HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
于 2015-11-27T05:06:29.223 回答
1

作为 dlambin 答案的补充

http.AllowAutoRedirect=false;

除此以外

HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;

它将向初始 url 发出另一个请求,您将无法检索 url2。

于 2012-02-25T12:07:20.270 回答
0

您需要使用 HTTPWebRequest 并执行 POST。此链接应该可以帮助您入门。关键是,您需要查看您尝试发布的页面的 HTML 表单,以查看表单提交帖子所需的所有参数。

http://www.netomatix.com/httppostdata.aspx

http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx

于 2009-06-10T13:13:20.267 回答