我正在开发一个非常具体的网络抓取应用程序,它需要登录多个网站并从中检索一些数据。
我使用的 WebClient 已通过重写以下方法了解 cookie:
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
var castRequest = request as HttpWebRequest;
if (castRequest != null)
{
castRequest.CookieContainer = this.CookieContainer;
}
return request;
}
我可以通过常规 POST/GET 请求(通过网络客户端上适当的下载/上传方法)正常登录网站
目标网站使用 ajax ASP.Net 顶级表单,并且在您单击页面上的按钮后会启用一个状态变量。也就是说,当您单击按钮时,表单将被提交,状态将被更改,然后当它加载响应时,它就会包含我需要的信息。此时的状态修改也是持久的。如果我重新加载页面,甚至关闭选项卡并重新打开它,我需要的数据仍然存在,因为它与 ASP session 关联。一旦 ASP session 过期,您必须重新登录并单击按钮,服务器才会发送我需要的数据。
我在单击按钮时通过 Chrome 开发人员工具观看了提交的表单,并且我重新创建了表单提交,与我在 Chrome 网络监 window 口中看到的完全一样,但它仍然无法正确修改 View 状态。
所以我的问题是,如何模拟单击此按钮以便服务器修改 View 状态并返回我需要的值。
我不能为此使用网络浏览器控件,但如果它使事情变得更加容易,我可以使用 html 敏捷包(尽管我真的不想使用外部库)
按钮定义如下:
<form name="aspnetForm" method="post" action="enterurlhere..." id="aspnetForm">
<input type="image" name="ctl00$....." id="ctl00...." title="...." src="...." style="height:50px;border-width:0px;">
最佳答案
如果您的目标是 ASP.NET WebForms 站点:
1)您必须先登录才能导航到所需页面
2)在所需页面上有一个 UpdatePanel,其中有一个文本框,您需要在其中输入一些内容,然后提交该信息,如果该信息正确,您将得到“您所期望的”
我以前做过各种爬虫,因此以一个为基础,但剥离得相当好,很多,没有错误日志记录,验证您已登录,验证您在请求页面时仍然登录, HtmlAgilityPack、结构、代码简洁性、用户代理字符串随机化等,以使其保持简单,但您当然可以增强它:)无论如何,我已经在 Visual Studio 2013 中创建了一个 Web 项目(Web 表单)。知道它有一些登陆页面,包括用户注册等。然后你有“管理帐户”页面,这显然需要用户进行身份验证。在该页面上我添加了另一个 div,然后在其中放置了 UpdatePanel(这使得回发 ajaxified)。在 UpdatePanel 内,我放置了文本框、一个按钮和一个文字服务器控件。在后面的代码中,我为该按钮添加了一个单击事件处理程序:如果用户输入等于,假设“ secret ”,然后将一些文本放入文字中以指示操作成功。因此,应用程序必须首先登录,然后通过将 secret 短语提交到“管理帐户”页面来获取 secret 文本。
实际 getter :
using Pokemon.BL.Utils;
using System;
using System.Text;
using System.Web;
namespace Pokemon.BL
{
sealed class UrlFetcher : IDisposable
{
private static readonly UrlFetcher _instance;
private CGWebClient _cgWebClient;
private string loginPostString = "__EVENTTARGET={0}&__EVENTARGUMENT={1}&__VIEWSTATE={2}&__VIEWSTATEGENERATOR={3}&__EVENTVALIDATION={4}&ctl00$MainContent$Email={5}&ctl00$MainContent$Password={6}&ctl00$MainContent$ctl05={7}";
private string secretPhrasePostString = "__EVENTTARGET={0}&__EVENTARGUMENT={1}&__VIEWSTATE={2}&__VIEWSTATEGENERATOR={3}&__EVENTVALIDATION={4}&__ASYNCPOST=true&ctl00$MainContent$btnGetSecretPhrase=Button&ctl00$ctl08=ctl00$MainContent$UpdatePanel1|ctl00$MainContent$btnGetSecretPhrase&ctl00$MainContent$txtSecret={5}";
private UrlFetcher()
{
_cgWebClient = new CGWebClient();
}
static UrlFetcher()
{
_instance = new UrlFetcher();
}
#region Methods
public void LoginToSite(string email, string password)
{
var loginUrl = "http://localhost:53998/Account/Login";
byte[] response = _cgWebClient.DownloadData(loginUrl);
var content = Encoding.UTF8.GetString(response);
string eventTarget = ExtractToken("__EVENTTARGET", content);
string eventArg = ExtractToken("__EVENTARGUMENT", content);
string viewState = ExtractToken("__VIEWSTATE", content);
string viewStateGen = ExtractToken("__VIEWSTATEGENERATOR", content);
string eventValidation = ExtractToken("__EVENTVALIDATION", content);
string postData = string.Format(
loginPostString,
eventTarget,
eventArg,
viewState,
viewStateGen,
eventValidation,
email,
password,
"Log in"
);
_cgWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
response = _cgWebClient.UploadData(loginUrl, "POST", Encoding.UTF8.GetBytes(postData));
_cgWebClient.Headers.Remove("Content-Type");
}
public void GetSecretPhrase()
{
var loginUrl = "http://localhost:53998/Account/Manage";
byte[] response = _cgWebClient.DownloadData(loginUrl);
var content = Encoding.UTF8.GetString(response);
string eventTarget = ExtractToken("__EVENTTARGET", content);
string eventArg = ExtractToken("__EVENTARGUMENT", content);
string viewState = ExtractToken("__VIEWSTATE", content);
string viewStateGen = ExtractToken("__VIEWSTATEGENERATOR", content);
string eventValidation = ExtractToken("__EVENTVALIDATION", content);
string postData = string.Format(
secretPhrasePostString,
eventTarget,
eventArg,
viewState,
viewStateGen,
eventValidation,
"secret"
);
_cgWebClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
_cgWebClient.Headers.Add("X-Requested-With", "XMLHttpRequest");
response = _cgWebClient.UploadData(loginUrl, "POST", Encoding.UTF8.GetBytes(postData));
_cgWebClient.Headers.Remove("Content-Type");
_cgWebClient.Headers.Remove("X-Requested-With");
Console.WriteLine(Encoding.UTF8.GetString(response));
}
#region IDisposable Members
public void Dispose()
{
if (_cgWebClient != null)
{
_cgWebClient.Dispose();
}
}
#endregion
private string ExtractToken(string whatToExtract, string content)
{
string viewStateNameDelimiter = whatToExtract;
string valueDelimiter = "value=\"";
int viewStateNamePosition = content.IndexOf(viewStateNameDelimiter);
int viewStateValuePosition = content.IndexOf(valueDelimiter, viewStateNamePosition);
int viewStateStartPosition = viewStateValuePosition + valueDelimiter.Length;
int viewStateEndPosition = content.IndexOf("\"", viewStateStartPosition);
return HttpUtility.UrlEncode(
content.Substring(
viewStateStartPosition,
viewStateEndPosition - viewStateStartPosition
)
);
}
#endregion
#region Properties
public static UrlFetcher Instance { get { return _instance; } }
#endregion
}
}
WebClient 包装器:
using System;
using System.Collections.Generic;
using System.Net;
namespace Pokemon.BL.Utils
{
// http://codehelp.smartdev.eu/2009/05/08/improve-webclient-by-adding-useragent-and-cookies-to-your-requests/
public class CGWebClient : WebClient
{
private System.Net.CookieContainer cookieContainer;
private string userAgent;
private int timeout;
public System.Net.CookieContainer CookieContainer
{
get { return cookieContainer; }
set { cookieContainer = value; }
}
public string UserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
public int Timeout
{
get { return timeout; }
set { timeout = value; }
}
public CGWebClient()
{
timeout = -1;
userAgent = "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0";
cookieContainer = new CookieContainer();
}
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest request = base.GetWebRequest(address);
if (request.GetType() == typeof(HttpWebRequest))
{
((HttpWebRequest)request).CookieContainer = cookieContainer;
((HttpWebRequest)request).UserAgent = userAgent;
((HttpWebRequest)request).Timeout = timeout;
}
return request;
}
}
}
最后运行它:
UrlFetcher.Instance.LoginToSite("username", "password");
UrlFetcher.Instance.GetSecretPhrase();
UrlFetcher.Instance.Dispose();
这会将 secret 短语输出到控制台应用程序中。当然,您需要对其进行调整才能使其正常工作,例如根据目标站点运行的 ASP.NET 版本等:) 希望这有帮助:)
关于c# - 提交修改viewstate所需的ajax asp表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26456920/