Excel VBA浏览器自动化:网站搜索框没有元素ID

时间:2017-05-23 13:42:19

标签: excel vba browser automation

我正在尝试使用Excel VBA进行浏览器自动化,但网站的http://www.soccerstats.com/)搜索框没有元素ID,因此通常的技术不起作用。 这是我计划的代码:

    'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable we'll use as a counter
Dim result As String 'string variable that will hold our result link

'initiating a new instance of Internet Explorer and asigning it to objIE
Set objIE = New InternetExplorer

'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True

'navigate IE to this web page (a pretty neat search engine really)
objIE.navigate "http://www.soccerstats.com/"

'wait here a few seconds while the browser is busy
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

'in the search box put cell "A2" value, the word "in" and cell "C1" value
objIE.document.getElementById("dsearch").Value = "arsenal"

搜索框html代码为:

<input name="searchstring" style="border: currentColor; border-image: none; width: 90px; height: 20px; padding-left: 5px; background-color: rgb(238, 238, 238); text-color: gray;" onfocus="if (this.value == 'Search team...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search team...';}" type="text" maxlength="20" value="Search team...">

有人能告诉我如何为此搜索框添加值,然后点击搜索按钮吗?

1 个答案:

答案 0 :(得分:1)

您可以遍历输入元素并找到名为searchstring的元素,如下所示:

Dim ele As Object

For each ele in objIE.document.getElementsByTagName("input")
    If ele.Name = "searchstring" Then
        ele.Value = "Example Text"
    End if
Next ele