2015-07-10 52 views
0

我有要求必須通過代碼登錄網站,然後通過導航到某個位置下載報告文件。我已成功登錄,並且已到達文件下載的URL,但無法自動將其保存到磁盤。 下面是我的代碼使用.net自動下載文件

Imports SHDocVw 
Imports mshtml 
Imports System.Net 

Module Module1 
Dim HTMLDoc As HTMLDocument 
Dim MyBrowser As InternetExplorer 
Sub Main() 
    MyGmail() 
End Sub 
Sub MyGmail() 

    Dim MyHTML_Element As IHTMLElement 
    Dim MyURL As String 
    On Error GoTo Err_Clear 
    MyURL = "https://example.com/" 
    MyBrowser = New InternetExplorer 
    MyBrowser.Silent = True 
    MyBrowser.Navigate(MyURL) 
    MyBrowser.Visible = True 
    Do 
    Loop Until MyBrowser.ReadyState = tagREADYSTATE.READYSTATE_COMPLETE 
    HTMLDoc = MyBrowser.Document 
    HTMLDoc.all.txtUserID.Value = "[email protected]" 'Enter your email id here 
    HTMLDoc.all.txtPassword.Value = "test123" 'Enter your password here 

    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input") 
     If MyHTML_Element.Type = "submit" Then MyHTML_Element.click() : Exit For 
    Next 

    'Navigate to reports folder 
    Dim newReportURL As String 
    newReportURL = "https://some_static_url_to_navigate" 
    MyBrowser.Navigate(newReportURL) 
    Dim i As Integer 
    Dim reportURL As String 
    reportURL = "" 
    i = 0 
    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("a") 
     If DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).innerText = "Export" And i = 1 Then 

      reportURL = DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).href 
     End If 

     If DirectCast(MyHTML_Element, mshtml.IHTMLAnchorElement).innerText = "Export" Then 
      i = i + 1 
     End If 


    Next 

    MyBrowser.Navigate(reportURL) 

    For Each MyHTML_Element In HTMLDoc.getElementsByTagName("input") 
     If MyHTML_Element.Type = "submit" Then 
      MyHTML_Element.click() : Exit For 
     End If 

    Next 


    Dim xlsReportURL As String 
    xlsReportURL = DirectCast(MyBrowser.Document, mshtml.IHTMLDocument).url 


Err_Clear: 
    If Err.Number <> 0 Then 
     Err.Clear() 
     Resume Next 
    End If 
End Sub 
End Module 

最後一個變量xlsReportURL包含我的報告的網址是.xls格式。我如何將此報告直接保存到我的硬盤上?

+0

你的C#似乎有點從一個我所知道的區別。 – Vladimirs

+0

我的錯誤..其實它vb .net – Tweety01

+0

此代碼看起來像Visual Basic,但不是c# –

回答

1

有一種方法DownloadFile()通過webclient。你應該嘗試使用該

代替BrowserControl

Download a file through the WebBrowser control

+0

我試過,但它創建新的瀏覽器對象,它將我重定向到登錄頁面 – Tweety01

+0

試試這個設置登錄信息:http:/ /stackoverflow.com/questions/17183703/using-webclient-or-webrequest-to-login-to-a-website-and-access-data – raddevus

+0

這不只是登錄,導航後登錄後動態生成報告的網址通過不同的頁面並在頁面上執行點擊事件。所有這些都可以使用WebClient完成嗎?請指教 – Tweety01