我需要来自不属于我的网站的一些信息,为了获取这些信息,我需要登录该网站以收集信息,这通过 HTML 表单进行。如何在 C# 中进行此经过身份验证的屏幕截图?
额外的信息:
- 基于 Cookie 的身份验证。
- 需要 POST 操作。
我需要来自不属于我的网站的一些信息,为了获取这些信息,我需要登录该网站以收集信息,这通过 HTML 表单进行。如何在 C# 中进行此经过身份验证的屏幕截图?
额外的信息:
您会像刚刚填写表格一样提出请求。例如,假设它是 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;
也许。
您可以使用WebBrowser控件。只需将站点的 URL 输入它,然后使用 DOM 将用户名和密码设置到正确的字段中,最后发送一个点击到提交按钮。这样,除了两个输入字段和提交按钮之外,您什么都不关心。没有 cookie 处理,没有原始 HTML 解析,没有 HTTP 嗅探——所有这些都由浏览器控件完成。
如果你这样做,还有一些建议:
在某些情况下,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;
作为 dlambin 答案的补充
http.AllowAutoRedirect=false;
除此以外
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
它将向初始 url 发出另一个请求,您将无法检索 url2。
您需要使用 HTTPWebRequest 并执行 POST。此链接应该可以帮助您入门。关键是,您需要查看您尝试发布的页面的 HTML 表单,以查看表单提交帖子所需的所有参数。
http://www.netomatix.com/httppostdata.aspx
http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx