2011-09-27 83 views
0

首先。我是编程的傀儡。VBA/javascript。脚本使浏览器动作自动化

我试图在Excel中使用Javascript和VBA来自动执行一些IE操作来转到某个页面并从该页面下载Excel文件,因为我需要每天都这样做。

a)....要下载的excel文件没有链接。 b)VBA脚本在自动登录时表现良好,但当IE进入第二页(不同的URL)时,它总是弹出运行时错误70-权限被拒绝。我试图修改IE选项中的安全性,但不工作。

c)....我使用JavaScript来做自动登录,它也运行得很好,但IE浏览器进入差异页面后,似乎停止工作。

d)....所以我怀疑它可能是我的脚本没有抓住新的HTML文档,当URL更改。

请帮忙。代码连接

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 bcuz it's js webpage? i dont 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

刷新页面(通过提交表单每次或使用.navigate),您需要重复您的“睡眠”循环,以便您等待页面完成加载,然后获取对文档对象的新引用。在您导航它之后,您会看到一个新页面,因此您不能继续使用“旧”文档参考。