.net 如何使用HttpWebRequest登录网站

.net 如何使用HttpWebRequest登录网站,.net,c#-4.0,httpwebrequest,.net,C# 4.0,Httpwebrequest,有人能帮我弄清楚如何使用HttpWebRequest登录页面,然后刮取页面吗。我使用的代码不仅在登录页面上写出标记,而且无法登录…我尝试登录的网站是基于php的网站 // first, request the login form to get the viewstate value HttpWebRequest webRequest = WebRequest.Create("loginPageUrl") as HttpWebRequest; St

有人能帮我弄清楚如何使用HttpWebRequest登录页面,然后刮取页面吗。我使用的代码不仅在登录页面上写出标记,而且无法登录…我尝试登录的网站是基于php的网站

        // first, request the login form to get the viewstate value
        HttpWebRequest webRequest = WebRequest.Create("loginPageUrl") as HttpWebRequest;
        StreamReader responseReader = new StreamReader(
              webRequest.GetResponse().GetResponseStream()
           );
        string responseData = responseReader.ReadToEnd();
        responseReader.Close();


        string postData = String.Format("Username={0}&Password={1}", "user", "pwd");

        // have a cookie container ready to receive the forms auth cookie
        CookieContainer cookies = new CookieContainer();

        // now post to the login form
        webRequest = WebRequest.Create("loginPostUrl") as HttpWebRequest;
        webRequest.Method = "POST";
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.CookieContainer = cookies;

        // write the form values into the request message
        StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
        requestWriter.Write(postData);
        requestWriter.Close();

        // we don't need the contents of the response, just the cookie it issues
        webRequest.GetResponse().Close();

        // now we can send out cookie along with a request for the protected page
        webRequest = WebRequest.Create("PageToScrapeUrl") as HttpWebRequest;
        webRequest.CookieContainer = cookies;
        responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());

        // and read the response
        responseData = responseReader.ReadToEnd();
        responseReader.Close();

        Console.WriteLine(responseData);
        Console.ReadKey();

使用WireShark等工具捕获实际的浏览器流量,查看它发送的内容,然后返回。然后在代码中复制行为。代码的基础是正确的,您只需调整它。

使用WireShark等工具捕获实际的浏览器流量,查看它发送的内容,然后返回。然后在代码中复制行为。你的代码基础是正确的,你只需要调整它。

很少有带有auth的页面是用来刮取的,并且经常违反ToS。更常见的是,如果该数据打算像这样使用,那么将有一个编程API。使用API。对于允许刮取的情况:您是否与fiddler检查了流量?您必须使用浏览器使用原始页面分析成功登录并模拟webrequest。可能还有其他一些字段被发布到服务器上?你能给我们这个站点的url吗?这将更容易看出你错在哪里,因为登录到网站没有银弹有时网站本身也在改变它-当它被修改时。很少有带有auth的页面是打算被删除的,并且经常违反ToS。更常见的是,如果该数据打算像这样使用,那么将有一个编程API。使用API。对于允许刮取的情况:您是否与fiddler检查了流量?您必须使用浏览器使用原始页面分析成功登录并模拟webrequest。可能还有其他一些字段被发布到服务器上?你能给我们这个站点的url吗?这将更容易看出你错在哪里,因为登录网站没有银弹有时网站本身也在改变它-当它被修改时。我的回答有什么问题,如果你投反对票,请评论。我的回答有什么问题,如果你投反对票,请评论。