WebBrowser帮助 - 导航到URL,等待一段时间,然后单击按钮

时间:2014-08-29 13:29:01

标签: c#

我需要从网站上获取下载链接。 得到它我需要等待10秒,直到它可以点击。 是否可以通过WebBrowser()获取下载链接?

这是按钮的来源。

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

这是我尝试过的:

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();

这里有什么问题?

编辑 - 尝试了这个,但仍然无法正常工作 - 顺便说一下,我觉得我的代码搞砸了我是noob :)。

        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();
        }

1 个答案:

答案 0 :(得分:0)

我对回答这个问题并不满意,但希望这能说明如何以不同的方式做到这一点;

a)您不需要使用Web浏览器控件下载网页

b)你不需要这些忙碌的等待等待的东西..

c)显示使用 HttpClient HtmlAgilityPack + async / await

可能会有所帮助

现在,编写如下方法

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 的方法中调用它,如下所示

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

PS:这个答案需要HtmlAgilityPack来解析返回的html。