다음 웹 사이트에서 일부 데이터를 긁어 내고 싶습니다.
웹 사이트에는 탁구에 대한 데이터가 포함되어 있습니다. 실제 시즌은 로그인없이 마지막 시즌에만 로그인 할 수 있습니다. 실제 시즌에는 이미 데이터를 가져 오는 코드를 만들었고 정상적으로 작동합니다. HtmlAgilityPack에서 HttpClient를 사용하고 있습니다. 코드는 다음과 같습니다.
HttpClient http = new HttpClient();
var response = await http.GetByteArrayAsync(website);
String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
source = WebUtility.HtmlDecode(source);
HtmlDocument resultat = new HtmlDocument();
resultat.LoadHtml(source);
Do something to get the relevant data from resultat by scanning the DocumentNodes from resultat...
이제 로그인이 필요한 웹 사이트에서 데이터를 가져오고 싶습니다. 누구든지 웹 사이트에 로그인하여 데이터를 얻는 방법에 대한 아이디어가 있습니까? 로그인은 "Ergebnishistorie freischalten ..."을 클릭 한 다음 사용자 이름과 암호를 입력하여 수행해야합니다.
웹 사이트에 대한 로그인을 수행하는 방법은 다양하며 특정 사이트에서 사용하는 인증 방법 (양식 인증, 기본 인증, Windows 자동 작성 등)에 따라 다릅니다. 일반적으로 웹 사이트는 FormsAuthentication을 사용합니다.
HttpClient를 사용하여 표준 FormsAuthentication 웹 사이트에서 로그인을 수행하려면 쿠키에 인증 데이터가 설정되므로 CookieContainer를 설정해야합니다.
특정 예에서 로그인 양식은 HTTPS의 페이지 중 하나에 POST를 수행합니다. https://wttv.click-tt.de/cgi-bin/WebObjects/nuLigaTTDE.woa/wa/teamPortrait?teamtable=1673669&pageState = rueckrunde & championship = SK + Bez. + BB + 13 % 2F14 & group = 204559 를 예로들 수 있습니다. 이것은 HttpClient를 사용하여 요청을하는 코드입니다.
var baseAddress = new Uri("https://wttv.click-tt.de/");
var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
{
//usually i make a standard request without authentication, eg: to the home page.
//by doing this request you store some initial cookie values, that might be used in the subsequent login request and checked by the server
var homePageResult = client.GetAsync("/");
homePageResult.Result.EnsureSuccessStatusCode();
var content = new FormUrlEncodedContent(new[]
{
//the name of the form values must be the name of <input /> tags of the login form, in this case the tag is <input type="text" name="username">
new KeyValuePair<string, string>("username", "username"),
new KeyValuePair<string, string>("password", "password"),
});
var loginResult = client.PostAsync("/cgi-bin/WebObjects/nuLigaTTDE.woa/wa/teamPortrait?teamtable=1673669&pageState=rueckrunde&championship=SK+Bez.+BB+13%2F14&group=204559", content).Result;
loginResult.EnsureSuccessStatusCode();
//make the subsequent web requests using the same HttpClient object
}
그러나 많은 웹 사이트에서는 일부 자바 스크립트로드 된 양식 값 또는 더 많은 captcha 컨트롤을 사용하며 분명히이 솔루션이 작동하지 않습니다. WebBrowser 컨트롤에서 폼 필드에 대한 사용자 입력을 자동화 한 다음 로그인 단추를 클릭하여이 작업을 수행 할 수 있습니다.이 링크에는 예제가 있습니다. https://social.msdn.microsoft.com/Forums/vstudio/en- US / 0b77ca8c-48ce-4fa8-9367-c7491aa359b0 / yahoo-login-via-systemnetsockets-namespace? forum = vbgeneral ).
일반적으로 웹 사이트에서 로그인하는 방법을 검사하려면 Fiddler를 사용 하십시오 . http://www.telerik.com/fiddler : 웹 사이트에서 로그인 버튼을 클릭하면 Fiddler를보고 로그인 요청을 찾습니다 (일반적으로 첫 번째 요청은 "로그인"버튼을 클릭 한 직후이며 일반적으로 POST 요청입니다.
그런 다음 요청 데이터를 검사하고 (요청을 선택하고 "Inspector"- "TextView"탭으로 이동) 코드에서 요청을 복제하십시오.
왼쪽 창에는 모든 요청이 Fiddler에 의해 가로 채어지고, 오른쪽 창에는 요청 및 응답 관리자가 있습니다 (맨 아래에는 요청 관리자가 있고, 아래에는 응답 관리자가 있습니다)
이전 WebRequest 클래스와 동일한 코드 : http://rextester.com/LLP86817
var cookieContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://wttv.click-tt.de/");
request.CookieContainer = cookieContainer;
//set the user agent and accept header values, to simulate a real web browser
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
//SET AUTOMATIC DECOMPRESSION
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
Console.WriteLine("FIRST RESPONSE");
Console.WriteLine();
using (WebResponse response = request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
request = (HttpWebRequest)HttpWebRequest.Create("https://wttv.click-tt.de/cgi-bin/WebObjects/nuLigaTTDE.woa/wa/teamPortrait?teamtable=1673669&pageState=rueckrunde&championship=SK+Bez.+BB+13%2F14&group=204559");
//set the cookie container object
request.CookieContainer = cookieContainer;
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
//set method POST and content type application/x-www-form-urlencoded
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
//SET AUTOMATIC DECOMPRESSION
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
//insert your username and password
string data = string.Format("username={0}&password={1}", "username", "password");
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
}
Console.WriteLine("LOGIN RESPONSE");
Console.WriteLine();
using (WebResponse response = request.GetResponse())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(sr.ReadToEnd());
}
}
//request = (HttpWebRequest)HttpWebRequest.Create("INTERNAL PROTECTED PAGE ADDRESS");
//After a successful login, you must use the same cookie container for all request
//request.CookieContainer = cookieContainer;
//....