需要有关创建发布请求和获取值的指导

时间:2013-07-17 15:42:17

标签: c# web-scraping postback paging

我正在尝试创建一个我需要抓取数据的Web服务。问题是,我需要从中获取数据的网站是在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: enter image description here

1 个答案:

答案 0 :(得分:0)

您要发布的网站是否有任何预期的cookie?当您手动使用站点时,请检查Fiddler以查看是否有任何cookie附加到POST。

如果是这样,您将需要在发出GET请求时收到的cookie并将其附加到第二个POST请求。有关如何使用WebClient执行此操作的信息,请参阅Using CookieContainer with WebClient class