Tam*_*man 22 c# forms login web-scraping
我需要来自不属于我的网站的一些信息,以获取我需要登录网站收集信息的这些信息,这通过HTML表单进行.如何在C#中进行经过身份验证的屏幕截图?
额外的信息:
dla*_*lin 23
你提出请求就像你刚填写表格一样.例如,假设它是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;
Run Code Online (Sandbox Code Playgroud)
也许.
您可以使用WebBrowser控件.只需输入网站的URL,然后使用DOM将用户名和密码设置到正确的字段中,最后发送一个点击进入提交按钮.这样你除了两个输入字段和提交按钮之外什么都不关心.没有cookie处理,没有原始HTML解析,没有HTTP嗅探 - 所有这些都是由浏览器控件完成的.
如果你这样做,还有一些建议: