我正在尝试创建一个需要从中抓取数据的网络服务。问题是我需要从中获取数据的网站位于一个包含分页的 asp gridview 中。所以我需要的是,读取 html,回发到页面 - 所以它会给我gridview 的下一页,然后获取新的 html 代码(响应),我可以从中解析并获取我需要的数据...
我尝试了很多方法来解决这个问题,但没有成功。那么你能告诉我我哪里做错了吗?
代码:
[WebMethod]
public string eNabavki2()
{
WebClient client = new WebClient();
client.Encoding = Encoding.UTF8;
string htmlCode = client.DownloadString("https://site.com/Default.aspx");
string vsk = getBetween(htmlCode, "id=\"__VIEWSTATEKEY\" value=\"", "\" />");
WebRequest request = WebRequest.Create("https://site.com/Default.aspx");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var webRequest = (HttpWebRequest)request;
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"; //Googlebot/2.1 (+http://www.googlebot.com/bot.html)
//set form data
string postData = string.Format("__EVENTTARGET={0}" +
"&__EVENTARGUMENT={1}" +
"&__LASTFOCUS={2}"+
"&__VIEWSTATEKEY={3}"+
"&__VIEWSTATE={4}"+
"&__SCROLLPOSITIONX={5}"+
"&__SCROLLPOSITIONY={6}"+
"&ctl00$ctl00$cphGlobal$cphPublicAccess$publicCFTenders$dgPublicCallForTender$ctl13$ddlPageSelector={7}",
System.Web.HttpUtility.UrlEncode("ctl00$ctl00$cphGlobal$cphPublicAccess$publicCFTenders$dgPublicCallForTender$ctl13$ddlPageSelector"),
/*1*/string.Empty,
/*2*/string.Empty,
/*3*/string.Empty,//vsk
/*4*/string.Empty,
/*5*/"0",
/*6*/"383",
/*7*/"2");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
//send the form data to the request stream
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
var response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
好吧,就这么几件事,在 postData 字符串中,我包含了我在发送的页面上可以找到的所有内容。我为此使用了 fidler,以及它给我的所有(26)个参数。我真正需要的是 pageSelector (改变他的值)
我还注意到html代码中有一个__VIEWSTATEKEY,它每次都会得到不同的值。你可以看到我首先尝试从 html(vsk 字符串)获取该值,但这并没有改变任何东西..
很抱歉,但我不熟悉这个帖子/请求的事情。但我需要它用于大学项目,所以如果有人可以帮助我解决这个问题......
编辑: 这是 fidler 为我提供的标题的 prt scr:
您发布帖子的网站是否需要任何 cookie?检查 Fiddler,看看当您手动使用该网站时,POST 中是否附加了任何 cookie。
如果是这样,您将需要发出 GET 请求时收到的 cookie,并将它们附加到第二个 POST 请求。有关如何使用 WebClient 执行此操作的信息,请参阅将 CookieContainer 与 WebClient 类一起使用。