【问题标题】:Automate download of file using .net使用 .net 自动下载文件
【发布时间】:2015-07-10 12:24:12
【问题描述】:

我有一个要求,我必须通过代码登录到站点,然后通过导航到某个位置下载报告文件。我已成功登录并访问了文件下载的 URL,但无法自动将其保存到磁盘。 下面是我的代码

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 = "xyz@example.com" '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 包含我的报告 url,它是 .xls 格式的。如何将此报告直接保存到我的硬盘?

【问题讨论】:

  • 您的 C# 似乎与我所知道的有点不同。
  • 我的错误.. 它实际上是 vb .net
  • 这段代码看起来像 Visual Basic,但不像 c#

标签: .net vb.net


【解决方案1】:

有一个通过webclient的方法DownloadFile()。您应该尝试使用它而不是 BrowserControl

Download a file through the WebBrowser control

【讨论】:

  • 我试过了,但是当它创建新的浏览器对象时,它会将我重定向到登录页面
  • 试试这个设置登录信息:stackoverflow.com/questions/17183703/…
  • 不只是登录,报表的url是登录后在不同页面导航并在页面上执行点击事件后动态生成的。这一切都可以用WebClient完成吗?请指教
猜你喜欢
  • 2012-07-13
  • 1970-01-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 2013-07-30
  • 1970-01-01
相关资源
最近更新 更多