2015-09-02 136 views
3

我是一名VBA新手,也是Stack Overflow的新手,儘管我一直在這裏閱讀帖子一段時間。我已經搜索了很多關於我的編碼問題的答案,但我似乎無法找到答案。我試圖登錄到一個網站,導航到一個頁面,然後從該頁面中抓取數據。我已經開始構建我在互聯網上找到的代碼。我似乎無法讓IE瀏覽器在使用「獲取元素」查找其ID後,將我的憑證放入適當的用戶和密碼箱中。結果是運行時錯誤424 - 對象必需。預先感謝您的幫助。Excel VBA登錄IE網站

'Open IE, navigate to the desired page and loop until fully loaded 
    Set IE = CreateObject("InternetExplorer.Application") 
    site = "https://www.ivolatility.com/login.j" 

    With IE 
     .Visible = True 
     .navigate site 
    Do Until Not IE.Busy And IE.readyState = 4 
     DoEvents 
    Loop 

    End With 

'Input the userid and password 
    IE.Document.getElementById("username").Value = "xxxxxx" 
    IE.Document.getElementById("password").Value = "xxxxxx" 

'Click the "Search" button 
    IE.Document.getElementById("login_go").Click 

    Do Until Not IE.Busy And IE.readyState = 4 
     DoEvents 
    Loop 
+0

這些元素沒有這樣的ID。 –

回答

2

您正在嘗試使用HTML輸入元素的ID的儘管有時你會看到兩個不一定相同。

<input type="text" id="username" name="username" value="" size="10" class="s2" maxlength="63 "> 

但這不是他在這裏的情況。你需要通過理論名稱而不是id來處理元素。

dim n as long 'this belongs at hte top witrh the other Dims 

'Input the userid and password 
For n = 0 To ie.document.getelementsbytagname("input").Length - 1 
    With ie.document.getelementsbytagname("input")(n) 
     Select Case LCase(.Name) 
      Case "username" 
       .Value = "xxxxxx" 
      Case "password" 
       .Value = "zzzzzz" 
      Case "login_go" 
       .Click 
       n = 99999 
      Case Else 
       'ignore 
     End Select 
    End With 
Next n 
Do While ie.Busy Or ie.readyState <> 4: DoEvents: Loop 

的點擊能在這種情況下,因爲提交來自名爲用戶名密碼輸入元素之後。

1

由於有與ID爲「用戶名」,「密碼」和「login_go」沒有HTML元素,空的Value不能設置。

如果文檔的結構保持不變的時候,你可以用索引訪問這些元素:

IE.Document.getElementsByTagName("input")(3).Value = "xxxxxx"  
IE.Document.getElementsByTagName("input")(8).Value = "xxxxxx" 
... 
IE.Document.getElementsByTagName("form")(1).Submit