循环浏览网站链接并将PDF发送到我的计算机



本主题与循环链接和下载PDF';s

我正在尝试将当前的VBA代码转换为VBScript。我已经明白,我有来删除变量类型(As…Dim语句的一部分(,并使用CreatObject来获取这些对象,但否则一切都应该按原样移植。DoEvents也必须被类似Wscript.sleep的东西所取代。

我遇到了一些问题。当前运行VBS文件时,我收到一个错误,上面写着"需要对象:'MSHTML'"。指向第65行,这里有Set hDoc = MSHTML.HTMLDocument。我试过在谷歌上搜索,但对这次没有任何帮助。

我应该如何处理这个?

DownloadFiles("https://www.nordicwater.com/products/waste-water/")
Sub DownloadFiles(p_sURL)
Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp 
Dim hDoc
Dim Anchors 
Dim Anchor 
Dim sPath
Dim wholeURL
Dim internet
Dim internetdata
Dim internetlink
Dim internetinnerlink 
Dim arrLinks 
Dim sLink 
Dim iLinkCount 
Dim iCounter 
Dim sLinks
Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = False
internet.navigate (p_sURL)
Do Until internet.ReadyState = 4
Wscript.Sleep 100
Loop
Set internetdata = internet.document
Set internetlink = internetdata.getElementsByTagName("a")
i = 1
For Each internetinnerlink In internetlink
If Left(internetinnerlink, 36) = "https://www.nordicwater.com/product/" Then
If sLinks <> "" Then sLinks = sLinks & vbCrLf
sLinks = sLinks & internetinnerlink.href
i = i + 1
Else
End If
Next
wholeURL = "https://www.nordicwater.com/"
sPath = "C:temp"
arrLinks = Split(sLinks, vbCrLf)
iLinkCount = UBound(arrLinks) + 1
For iCounter = 1 To iLinkCount
sLink = arrLinks(iCounter - 1)
'Get the directory listing
xHttp.Open "GET", sLink
xHttp.send
'Wait for the page to load
Do Until xHttp.ReadyState = 4
Wscript.Sleep 100
Loop
'Put the page in an HTML document
Set hDoc = MSHTML.HTMLDocument
hDoc.body.innerHTML = xHttp.responseText
'Loop through the hyperlinks on the directory listing
Set Anchors = hDoc.getElementsByTagName("a")
For Each Anchor In Anchors
'test the pathname to see if it matches your pattern
If Anchor.pathname Like "*.pdf" Then
xHttp.Open "GET", wholeURL & Anchor.pathname, False
xHttp.send
With CreateObject("Adodb.Stream")
.Type = 1
.Open
.write xHttp.responseBody
.SaveToFile sPath & getName(wholeURL & Anchor.pathname), 2 '//overwrite
End With
End If
Next
Next
End Sub

功能:

Function getName(pf)
getName = Split(pf, "/")(UBound(Split(pf, "/")))
End Function

使用:而不是Set hDoc = MSHTML.HTMLDocument

Set hDoc = CreateObject("htmlfile")

在VBA/VB6中,可以指定变量和对象类型,但不能使用VBScript。您必须使用CreateObject(或GetObject:GetObject函数(来实例化MSHTML.HTMLDocumentMicrosoft.XMLHTTPInternetExplorer.Application等对象,而不是使用Dim objIE As InternetExplorer.Application来声明这些对象。

另一个变化:

If Anchor.pathname Like "*.pdf" Then

可以使用StrComp函数编写:

If StrComp(Right(Anchor.pathname, 4), ".pdf", vbTextCompare) = 0 Then

或使用InStr函数:

If InStr(Anchor.pathname, ".pdf") > 0 Then

此外,在你的潜艇开始时,你要做以下事情:

Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim xHttp 

在给变量赋值或对象之前,应该先声明变量。在VBScript中,这是非常轻松的,您的代码可以工作,因为VBScript会为您创建未定义的变量,但在使用变量之前最好先Dim

除了Wscript.sleep命令外,您的VBScript代码将在VB6/VBA中工作,因此您可以在VB6或VBA应用程序(如Excel(中调试脚本。

最新更新