首先。我是编程中的假人。
我试图在Excel中使用JavaScript和VBA来自动执行某些IE操作以转到某个页面并从该页面下载Excel文件,因为我需要每天都这样做。
要下载的Excel文件没有链接。
VBA脚本在自动登录方面做得很好,但是当IE进入第二页(不同的URL)时,它总是会弹出运行时错误70 - 权限被拒绝。我试图修改IE选项中的安全性但不起作用。
我使用JavaScript进行自动登录,效果也很好,但是在IE进入差异页后,它似乎停止了工作。
所以我怀疑可能是我的脚本在网址更改时没有抓取新的html文档。
VBA:
Sub vbadownload()
Dim objIE As SHDocVw.InternetExplorer ' internet controls
Dim htmlDoc As MSHTML.HTMLDocument ' html object lib
Dim htmlInput As MSHTML.HTMLInputElement
Dim htmlDiv As MSHTML.HTMLDivElement
Dim htmlColl As MSHTML.IHTMLElementCollection
Set objIE = New SHDocVw.InternetExplorer
''''''''''' first log in
With objIE
.Navigate "mainpage.com" ' log in page
.Visible = 1
Do While .READYSTATE <> 4: DoEvents: Loop
Application.Wait (Now + TimeValue("0:00:01"))
'set user name and password
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("INPUT")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If htmlInput.Name = "username" Then
htmlInput.Value = "xxxx" 'username
Else
If htmlInput.Name = "password" Then
htmlInput.Value = "xxxx" 'password
End If
End If
Next htmlInput
'click login
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("input")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlInput In htmlColl
If Trim(htmlInput.Type) = "submit" Then
htmlInput.Click 'click
Exit For
End If
Next htmlInput
' now it goes to second page after submit
' and I want click some button on second page, it says permission denied.
' so how do i make below codes work on current page without typing new url. ( as the url actually does not change, I guess because it's js webpage? I don't know)
Set htmlDoc = .Document
Set htmlColl = htmlDoc.getElementsByTagName("div")
Do While htmlDoc.READYSTATE <> "complete": DoEvents: Loop
For Each htmlDiv In htmlColl
If Trim(htmlDiv.ID) = "123" Then
htmlDiv.Click 'click
Exit For
End If
Next htmlDiv
End With
的JavaScript
var ie = new ActiveXObject("InternetExplorer.Application");
ie.visible=true;
ie.navigate("www.sample.com");
while(ie.busy)(WScript.sleep(100));
var doc1 = ie.document;
var window1 = doc1.window;
var form1 = doc1.forms[0];
form1.username.value="xxx";
form1.password.value="xxxx";
form1.submit();
/* again, from here, it goes to second page, and it stops working.
* how do I get/parse current html document? */
var div1 = doc1.getElementsByTagName("div");
for (var i=0; i<div1.length; ++i)
{
if (div1[i].className="fff")
{div1[i].click()}
}
答案 0 :(得分:0)
每次刷新页面时(通过提交表单或使用.navigate),您需要重复“睡眠”循环,以便等待页面完成加载,然后获取对文档对象的新引用。导航后它是一个新页面,因此您不能继续使用“旧”文档参考。