2014-08-29 2 views
0

사이트에서 다운로드 링크를 얻어야합니다. 클릭하면 사용할 수있을 때까지 10 초 정도 기다려야합니다. WebBrowser()와 함께 다운로드 링크를 얻을 수 있습니까?WebBrowser help - URL로 이동하고 잠시 기다린 다음 버튼을 클릭하십시오.

이것은 버튼의 소스입니다.

WebBrowser wb = new WebBrowser(); 
wb.ScriptErrorsSuppressed = true; 
wb.AllowNavigation = true; 
wb.Navigate(url); 
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); 
while (wb.ReadyState != WebBrowserReadyState.Complete) 
{ 
    Application.DoEvents(); 
} 
Thread.Sleep(10000); 
HtmlElement element = wb.Document.GetElementById("btn_download"); 
element.InvokeMember("submit"); 
while (wb.ReadyState != WebBrowserReadyState.Complete) 
{ 
    Application.DoEvents(); 
} 
string x = wb.Url.ToString(); 

여기에 잘못된 것입니다 :

<input type="submit" id="btn_download" class="btn btn-primary txt-bold" value="Download File"> 

이 내가 시도 무엇인가?

편집 됨 - BTW 내가 작은 내가

 public void WebBrowser() 
     { 
       WebBrowser wb = new WebBrowser(); 
       wb.ScriptErrorsSuppressed = true; 
       wb.AllowNavigation = true; 
       wb.Navigate(URL); 
       wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); 
       while (wb.ReadyState != WebBrowserReadyState.Complete) 
        Application.DoEvents(); 
       wb.Dispose(); 
} 

    public void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) 
      { 
       WebBrowser wb = (WebBrowser)sender; 
       string x = wb.Url.ToString(); 
       if (!x.Contains("server")) // download link must conatin server 
       { 
        System.Timers.Timer t = new System.Timers.Timer(); 
        t.Interval = 10000; 
        t.AutoReset = true; 
        t.Elapsed += new ElapsedEventHandler(TimerElapsed); 
        t.Start(); 
        HtmlElement element = wb.Document.GetElementById("btn_download"); 
        element.InvokeMember("Click"); 
        while (wb.ReadyState != WebBrowserReadyState.Complete) 
         Application.DoEvents(); 
       } 
       else 
        MessageBox.Show(x); 
       } 
     public void TimerElapsed(object sender, ElapsedEventArgs e) 
     { 
       Application.DoEvents(); 
     } 
+0

정확히 무엇이 작동하지 않는지 우리에게 말하지 않을 때, 무엇이 잘못 됐는지를 말하기는 어렵습니다. 하지만 먼저 InvokeMember ("Click")을 사용해야한다고 생각합니다. InvokeMember ("submit") 대신. 두 번째로 클릭 후 URL을 읽으려고합니다. 하지만 브라우저를 호출하면 새 탐색이 시작됩니다. 따라서 DocumentCompleted-Handler의 시작 부분에서 실제 URL을 찾아 대기 사이트인지 다운로드 사이트인지 확인해야합니다. 기다리고 있으면 호출하십시오. 다운로드 한 다음 문자열 x = wb.Url.ToString(); – netblognet

+1

UI 스레드 ('Thread.Sleep (10000);')를 차단하고 있습니다. 그 기간 동안 웹 브라우저는 아무 것도 할 수 없습니다. –

+0

차단을 피하기 위해 타이머를 사용할 수 있습니다. 이것 좀 봐 : http://stackoverflow.com/questions/8496275/c-sharp-wait-for-a-while-without-blocking – netblognet

답변

0

나는이 대답 편안하지 않다 : 멍청한 놈에게있어 코드를 엉망으로 생각하지만,이 보여줄 수 있기를 바랍니다 - 여전히 작동하지 않는이 시도하지만, 그것이 어떻게 다르게 행해질 수 있는지;

a) 귀하가 뭔가를 기다리고에 당신이 바쁜-waitings 필요하지 않습니다) WebBrowser 컨트롤 오 웹 페이지를

B를 다운로드 사용할 필요가 없습니다 ..

C) 그것은 할 수있다

다음과 같은 HttpClient를, HtmlAgilityPack + 비동기/이제

기다리고, 쓰기 방법을 사용하는 방법을 보여줍니다하는 데 도움이 방법에

async Task<string> DownloadLink(string linkID) 
{ 
    string url = "http://sfshare.se/" + linkID; 
    using (var clientHandler = new HttpClientHandler() { CookieContainer = new CookieContainer(), AllowAutoRedirect = false }) 
    { 
     using (HttpClient client = new HttpClient(clientHandler)) 
     { 
      //download html 
      var html = await client.GetStringAsync(url).ConfigureAwait(false); 

      //Parse it 
      var doc = new HtmlAgilityPack.HtmlDocument(); 
      doc.LoadHtml(html); 

      var inputs = doc.DocumentNode.SelectNodes("//input[@type='hidden']") 
          .ToDictionary(i => i.Attributes["name"].Value, i => i.Attributes["value"].Value); 
      inputs["referer"] = url; 

      //Wait 10 seconds 
      await Task.Delay(1000 * 10).ConfigureAwait(false); 

      //Click :) Send the hidden inputs. op=download2&id=ssmwvrxx815l...... 
      var response = await client.SendAsync(new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(inputs) }) 
             .ConfigureAwait(false); 

      //Get the download url 
      var downloadUri = response.Headers.Location.ToString(); 

      var localFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Path.GetFileName(downloadUri)); 

      //Download 
      using (var file = File.Create(localFileName)) 
      { 
       var stream = await client.GetStreamAsync(downloadUri).ConfigureAwait(false); ; 
       await stream.CopyToAsync(file).ConfigureAwait(false); 
      } 

      return localFileName; 
     } 
    } 
} 

하고 호출이

async void Test() 
{ 
    var downloadedFile = await DownloadLink("vydjxq40g503"); 
} 

PS 아래와 같이 비동기 표시이 응답이 리턴 된 HTML을 파싱 HtmlAgilityPack 필요하다.

+0

고마워.하지만 난 이미 알아.이 문제는 내가 rar 같은 다른 종류의 파일을 다운로드하려고 할 때이다. 링크 ID : ssmwvrxx815l – Dorel

+0

@ 도르 나는 모든 종류의 링크를 다운로드하는 대답을 업데이 트 .... – EZI

+0

와우 감사합니다,하지만 난 코드와 함께,이 오류주는 날 : 'HtmlAgilityPack.HtmlNodeCollection'하지 않습니다 'ToDictionary'에 대한 정의가 포함되어 있고 'HtmlAgilityPack.HtmlNodeCollection'유형의 첫 번째 인수를 수락하는 확장 메소드 'ToDictionary'가 없습니다. 지시어 또는 어셈블리 참조가 누락 되었습니까? – Dorel

관련 문제