有一个工作内部网站托管在与大多数内部网站不同的服务器上。该网站输出一些我想通过屏幕抓取获取的信息。我已经使用 asp.net (C#) 页面和其他内部站点上的 HTTPWebRequest 完成了屏幕抓取,但与大多数站点不同,此站点需要用户名和密码。用户名和密码不是 secret ,它们与登录页面,每个人都使用相同的登录信息。
我在网上看到了一些实现自动登录的示例,但这些都不是我所需要的。我想使用 aspx 页面登录该网站并从下一页检索一些数据。
我见过的示例涉及生成 cookie 并将登录数据发布到 HTTPWebRequest 流。我真的不知道在这种情况下该怎么做。
是否可以简单地填充表单字段并执行“submitw”按钮(以编程方式在幕后)。
以下是登录页面的部分代码:
<script>
//StartTranslate:NetLanguage
function window_onload() {
deleteCookie("BodyURL","/Net",0);
document.loginform.UserName.focus();
document.loginform.UserName.value=sUserName;
document.loginform.UserName.select();
}
function doSubmit() {
var sUserName = SMCookieGetUserName();
loginform.submit();
}
</script>
<form name="loginform" action="/Net//netportal.dll/SubmitLogin" method="post" >
<input class="textbox" type="text" name="UserName" id="UserName" maxlength="128" tabindex="1" >
<input class="textbox" type="password" name="Password" id="Password" maxlength="128" tabindex="2" >
<img onClick="doSubmit();" src='/net/PortalPages/Images/slogin.gif' onselectstart="return false;" tabindex="3">
<input type="hidden" value="" name="Timezone">
<input type="hidden" value="" name="redirect">
<input type="hidden" value="true" name="ExplicitLogin">
</form>
最佳答案
我认为对于这样的应用程序,您只需要像浏览器那样直接将帖子调用到服务器,而不是试图弄乱 html。您只需将预期的表单值发布到操作网址即可,它应该可以正常工作......
因此,在您的代码中,只需对/Net//netportal.dll/SubmitLogin 进行后调用并添加隐藏字段、用户名和密码,然后在服务器登录您后开始抓取。这是您的一些代码的示例可以用来开始...只需稍微改变一下。您还可以考虑使用 htmlagilitypack http://htmlagilitypack.codeplex.com/
private static string Post ( string Url, string Method, string Content, string ContentType = "application/json", WebHeaderCollection headers = null )
{
var address = new Uri(Url);
var request = WebRequest.Create(address) as HttpWebRequest;
request.Method = Method;
if (headers != null)
request.Headers.Add(headers);
if (!String.IsNullOrEmpty(Content))
{
var bytes = Encoding.UTF8.GetBytes(Content);
request.ContentLength = bytes.Length;
request.ContentType = ContentType;
using (var pStream = request.GetRequestStream())
{
pStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
return reader.ReadToEnd();
}
}
关于c# - 自动登录网站进行屏幕抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8101477/