Jas*_*zek 4 c# browser login-automation
我正在尝试自动登录 Photobucket 以供 API 使用,该项目需要使用存储的凭据自动下载照片。
API 生成用于登录的 URL,使用 Firebug 我可以看到正在发送/接收哪些请求和响应。
我的问题是,如何使用 HttpWebRequest 和 HttpWebResponse 来模拟 C# 中浏览器中发生的情况?
是否可以在 C# 应用程序中使用 Web 浏览器组件,填充用户名和密码字段并提交登录信息?
我以前做过这种事情,最后得到了一个很好的工具包来编写这些类型的应用程序。我已经使用这个工具包来处理非平凡的来回 Web 请求,所以这完全有可能,而且不是非常困难。
我很快发现从头开始执行HttpWebRequest/HttpWebResponse确实比我想要处理的级别低。我的工具完全基于Simon Mourier的HtmlAgilityPack。这是一个很好的工具集。它为您做了很多繁重的工作,并使解析获取的 HTML变得非常容易。如果您可以使用 XPath 查询,那么 HtmlAgilityPack 就是您想要开始的地方。它也可以很好地处理格式不佳的 HTML!
您仍然需要一个好的工具来帮助调试。除了调试器中的内容之外,能够检查 http/https 流量,因为它通过线路来回传输是无价的。由于您的代码将发出这些请求,而不是您的浏览器,因此 FireBug 不会对调试您的代码有多大帮助。有各种各样的数据包嗅探器工具,但对于 HTTP/HTTPS 调试,我认为您无法击败Fiddler 2的易用性和强大功能。最新版本甚至带有一个 Firefox 插件,可以快速通过 fiddler 转移请求并返回。因为它还可以充当无缝 HTTPS 代理,所以您也可以检查 HTTPS 流量。
试试看,我相信它们将成为您的黑客攻击中不可或缺的两个工具。
更新:添加了以下代码示例。这是从登录网站并为您保留相关 cookie 的一个不太大的“会话”类中提取的。我选择它是因为它不仅仅是一个简单的“请为我获取那个网页”的代码,而且它还有一两行 XPath 查询最终目标页面。
public bool Connect() {
if (string.IsNullOrEmpty(_Username)) { base.ThrowHelper(new SessionException("Username not specified.")); }
if (string.IsNullOrEmpty(_Password)) { base.ThrowHelper(new SessionException("Password not specified.")); }
_Cookies = new CookieContainer();
HtmlWeb webFetcher = new HtmlWeb();
webFetcher.UsingCache = false;
webFetcher.UseCookies = true;
HtmlWeb.PreRequestHandler justSetCookies = delegate(HttpWebRequest webRequest) {
SetRequestHeaders(webRequest, false);
return true;
};
HtmlWeb.PreRequestHandler postLoginInformation = delegate(HttpWebRequest webRequest) {
SetRequestHeaders(webRequest, false);
// before we let webGrabber get the response from the server, we must POST the login form's data
// This posted form data is *VERY* specific to the web site in question, and it must be exactly right,
// and exactly what the remote server is expecting, otherwise it will not work!
//
// You need to use an HTTP proxy/debugger such as Fiddler in order to adequately inspect the
// posted form data.
ASCIIEncoding encoding = new ASCIIEncoding();
string postDataString = string.Format("edit%5Bname%5D={0}&edit%5Bpass%5D={1}&edit%5Bform_id%5D=user_login&op=Log+in", _Username, _Password);
byte[] postData = encoding.GetBytes(postDataString);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postData.Length;
webRequest.Referer = Util.MakeUrlCore("/user"); // builds a proper-for-this-website referer string
using (Stream postStream = webRequest.GetRequestStream()) {
postStream.Write(postData, 0, postData.Length);
postStream.Close();
}
return true;
};
string loginUrl = Util.GetUrlCore(ProjectUrl.Login);
bool atEndOfRedirects = false;
string method = "POST";
webFetcher.PreRequest = postLoginInformation;
// this is trimmed...this was trimmed in order to handle one of those 'interesting'
// login processes...
webFetcher.PostResponse = delegate(HttpWebRequest webRequest, HttpWebResponse response) {
if (response.StatusCode == HttpStatusCode.Found) {
// the login process is forwarding us on...update the URL to move to...
loginUrl = response.Headers["Location"] as String;
method = "GET";
webFetcher.PreRequest = justSetCookies; // we only need to post cookies now, not all the login info
} else {
atEndOfRedirects = true;
}
foreach (Cookie cookie in response.Cookies) {
// *snip*
}
};
// Real work starts here:
HtmlDocument retrievedDocument = null;
while (!atEndOfRedirects) {
retrievedDocument = webFetcher.Load(loginUrl, method);
}
// ok, we're fully logged in. Check the returned HTML to see if we're sitting at an error page, or
// if we're successfully logged in.
if (retrievedDocument != null) {
HtmlNode errorNode = retrievedDocument.DocumentNode.SelectSingleNode("//div[contains(@class, 'error')]");
if (errorNode != null) { return false; }
}
return true;
}
public void SetRequestHeaders(HttpWebRequest webRequest) { SetRequestHeaders(webRequest, true); }
public void SetRequestHeaders(HttpWebRequest webRequest, bool allowAutoRedirect) {
try {
webRequest.AllowAutoRedirect = allowAutoRedirect;
webRequest.CookieContainer = _Cookies;
// the rest of this stuff is just to try and make our request *look* like FireFox.
webRequest.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3";
webRequest.Accept = @"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
webRequest.KeepAlive = true;
webRequest.Headers.Add(@"Accept-Language: en-us,en;q=0.5");
//webRequest.Headers.Add(@"Accept-Encoding: gzip,deflate");
}
catch (Exception ex) { base.ThrowHelper(ex); }
}
Run Code Online (Sandbox Code Playgroud)