VBA:下载多个文件所需的更好解决方案

时间:2014-02-13 22:45:36

标签: excel excel-vba selenium web-scraping download vba

我正在使用代码从网站下载csv文件。起初我尝试了创建InternetExplorer.Application等传统方法。这是最慢的方法。后来我想出了使用selenium Wrapper并创建了以下代码:

'Option Explicit

Sub ScripHistoryDownloader()
Flag5 = 0

Dim selDriver As Object
Dim URL As String, Scripcode As String
Dim StartDate As String, EndDate As String
Dim ScripHistPATH As String, DownloadedScripHistFILE As String, ScripHistFILE As String

ScripHistPATH = "R:\DataStore\003__ScripHistory\"

Scripcodez = "500010"

ScripHistFILE = ScripHistPATH & Scripcodez & ".csv"

StartDate = "01/01/1990"
URL = "http://www.bseindia.com/markets/equity/EQReports/StockPrcHistori.aspx?expandable=7&scripcode=" & Scripcodez & "&flag=sp&Submit=G"
ChromeDownloadsURL = "chrome://downloads/"


Set selDriver = CreateObject("SeleniumWrapper.WebDriver")
selDriver.Start "chrome", "http://www.google.com/"
selDriver.Open URL

selDriver.Type "id=ctl00_ContentPlaceHolder1_txtFromDate", StartDate
selDriver.findElementById("ctl00_ContentPlaceHolder1_btnSubmit").Click
selDriver.Click "id=ctl00_ContentPlaceHolder1_btnSubmit"
selDriver.clickAndWait "ctl00_ContentPlaceHolder1_btnDownload"
selDriver.Open ChromeDownloadsURL

'Checking if download is Completed.
downloadChecker:
    Application.Wait (Now + TimeValue("0:00:05"))
    DownloadedSHFileName = selDriver.findElementByClassName("name").Text
    If DownloadedSHFileName = "" Then
    GoTo downloadChecker
    End If

'Finding out where the file is downloaded and moving it to the desired location.
ChromeDownloadsHtml = selDriver.getHtmlSource
PathStartPosition = InStr(ChromeDownloadsHtml, "file:///")
PathStartPosition = PathStartPosition + 8
TempPathText = Mid(ChromeDownloadsHtml, PathStartPosition)
PathEndPosition = InStr(TempPathText, "/" & Scripcodez)
ScrambledPath = Left(TempPathText, PathEndPosition)
DownloadedScripHistFILE = Replace(ScrambledPath, "/", "\") & DownloadedSHFileName
selDriver.stop
MoveOrRenameFile DownloadedScripHistFILE, ScripHistFILE

Set selDriver = Nothing

Flag5 = 1
EndOfBhavCopyDownloader:
End Sub


'Function to Move or rename a file or Folder
Sub MoveOrRenameFile(SourcePath As String, DestinationPath As String)
    Name SourcePath As DestinationPath
End Sub

代码运行完全正常。我使用此代码每天下载大约3000个文件,并在计算机开启时触发。我的问题是,无论何时触发此代码,Chrome浏览器都会弹出,并且还会显示一个cmd窗口。我不希望在使用chrome时弹出窗口。无法隐藏浏览器和cmd窗口,就像我们使用ie.Visible = False中的InternetExplorer.Application隐藏IE一样。同时打开浏览器,导航......使得过程非常缓慢。 是否可以使用Microsoft.XMLHTTP对象执行上述代码操作?我已经使用过(在示例的帮助下)Microsoft.XMLHTTP对象但我没有在网站上填写表单生成一个文件,然后下载它。(我对使用它没有太多了解)...有人能告诉我一个方法吗?任何帮助表示赞赏。

注意:已发布的代码是我项目中的模块: My Entire Project for reference

0 个答案:

没有答案