2011-11-29 4 views
2

HttpWebRequest를 사용하여 페이지에 로그인 한 다음 페이지를 긁는 방법을 알아낼 수 있습니까? 이 코드는 단지 로그인 페이지에 마크 업을 작성하지만 로그인 할 수는 없습니다 ... 웹 사이트에 로그인하려고하면 PHP 기반 사이트입니다. WireShark로 같은 도구와HttpWebRequest를 사용하여 웹 사이트에 로그인하는 방법

 // 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(); 
+0

인증이있는 페이지가 거의 없기 때문에 ** 의도적으로 긁어 내고 ** ToS에 자주 위배됩니다. 일반적으로 데이터가 이와 같이 사용되도록 의도 된 경우 프로그래밍 방식의 API가 제공됩니다. API를 사용하십시오. –

+0

당신이 긁을 수있는 경우 : 피들러로 교통량을 확인 했습니까? 원본 페이지를 사용하여 브라우저로 성공적인 로그인을 분석하고 웹 요청을 시뮬레이트해야합니다. 서버에 게시되는 다른 필드가있을 수 있습니까? – Jan

+0

사이트의 URL을 제공해 주시겠습니까? 사이트에 로그인하기위한 은색 총알이 없으므로 어디에서 잘못되었는지 확인하는 것이 훨씬 쉽습니다 (때로는 사이트 자체가 변경되기도 함 - 개정 됨). –

답변

0

캡처 실제 브라우저 트래픽, 그것은 보내는보고, 다시 얻을. 그런 다음 코드에서 동작을 복사하십시오. 코드의 기반이 정확합니다. 코드를 수정해야합니다.

+0

내 대답에 문제가있는 경우, downvote하는 경우 의견을 말하십시오. –

관련 문제