2015-11-10 130 views
1

使用Excel VBA,我試圖登錄到網站。在登錄表單上輸入用戶名和密碼

這是我的代碼:

Dim HTMLDoc As HTMLDocument 
Dim oBrowser As InternetExplorer 
Sub Website_Login() 

Dim oHTML_Element As IHTMLElement 
Dim sURL As String 

sURL = "https://www.domain.com/login.html" 

Set oBrowser = New InternetExplorer 
'oBrowser.Silent = True 
'oBrowser.timeout = 60 
oBrowser.navigate sURL 
oBrowser.Visible = True 

Do 
Loop Until oBrowser.ReadyState = READYSTATE_COMPLETE 

Set HTMLDoc = oBrowser.Document 

With HTMLDoc 
    HTMLDoc.getElementById("username").Value = "user" 
    HTMLDoc.getElementById("password").Value = "password" 
End With 

For Each oHTML_Element In HTMLDoc.getElementsByTagName("input") 
    oHTML_Element.Click 
    Exit For 
Next 

oBrowser.Quit 

End Sub 

在這段代碼中的JavaScript指令工作。如果我進入頁面並輸入它們,它們就會工作。但是當我運行代碼時,IE會打開,但它不會進入用戶/密碼並點擊按鈕。

請幫忙嗎?

+0

需要看URL –

+1

我需要看到實際的URL –

+0

檢查瀏覽器不旺也,但是這看起來ok.Set ele2 = doc.getElementById( 「SEARCH_TERMS」) ele2.Value =「 TEST VAL「是我在過去使用的 –

回答

1

我剛測試過這段代碼,它工作正常。

唯一的區別是我用Late Binding(懶得設置所有的引用),我加了While .Busy到Loop等待URL加載。我還在按鈕點擊循環中將input更改爲button

Dim HTMLDoc As Object 'HTMLDocument 
Dim oBrowser As Object 'InternetExplorer 

Sub Website_Login() 

Dim oHTML_Element As Object 'IHTMLElement 
Dim sURL As String 

sURL = "https://www.mypage.com/login.html" 
Set oBrowser = CreateObject("InternetExplorer.Application") 'New InternetExplorer 
'oBrowser.Silent = True 
'oBrowser.timeout = 60 
oBrowser.navigate sURL 
oBrowser.Visible = True 

With oBrowser 
    Do While .Busy Or .ReadyState <> 4: Loop 
End With 


Set HTMLDoc = oBrowser.Document 

With HTMLDoc 
    HTMLDoc.getElementById("username").Value = "user" 
    HTMLDoc.getElementById("password").Value = "password" 
End With 

For Each oHTML_Element In HTMLDoc.getElementsByTagName("button") 
    If oHTML_Element.Name = "Submit" Then oHTML_Element.Click 
    Exit For 
Next 

oBrowser.Quit 

End Sub 
+0

哇,它也在這裏工作!你能否改變代碼中的sURL,以便我不會讓世界試圖登錄到網站? :-) 非常感謝你的幫助! –

+0

編輯它。我也將「輸入」更改爲「按鈕」。忘了補充說,第一次。如果確實如此,請標記爲已回答。 –

+0

謝謝,我注意到'輸入'必須改爲'按鈕',但它發生的頁面有不止一個按鈕,所以它沒有點擊正確的按鈕。 –

相關問題