VBA Internet Explorer下拉列表麻烦

我试图通过Excel使用VBA刮取一些数据。 我用VBA很生疏,但我对我的google-fu很有信心,5个多小时,还没有运气。 我已经看到很多使用下拉菜单的方法,但是没有一个可以和这个一起工作。 我已成功导航到https://www.kbb.com/used-cars/,但无法使用“年份”下拉菜单。 也许我不使用正确的ID /名称? 任何意见表示赞赏,让我知道,如果我留下任何重要的信息。

码:

Sub WebForumEntry() Dim IE As Object Set IE = CreateObject("InternetExplorer.Application") IE.Top = 0 IE.Left = 0 IE.Width = 800 IE.Height = 600 IE.AddressBar = 0 IE.StatusBar = 0 IE.Toolbar = 0 IE.Navigate "http://www.kbb.com" IE.Visible = True Do DoEvents Loop Until IE.ReadyState = 4 'Click on the "Used Car Values" link Set AllHyperlinks = IE.document.getelementsbytagname("A") For Each hyper_link In AllHyperlinks If hyper_link.innertext = "Used Car Prices" Then hyper_link.Click Exit For End If Next 'Select model year" Set e = IE.document.getElementbyid("yearDropdown") Dim o For Each o In e.Options If o.Value = "2012" Then o.Selected = True Exit For End If Next End Sub 

在HTML中没有Option标签供您select:

 <div class="form-group"> <select id="yearDropdown" name="yearId" class="dropdown-one year-dropdown" data-default-option="Year" data-preselected-value=""></select> </div> 

这些年是dynamic生成的,取决于你是否select新/使用等。所以你不能select一些不存在的东西 – 也许你可以直接设置值,例如:

 IE.document.getElementbyid("yearDropdown").value = "2012" 

编辑

请注意,您的原始代码中存在一个问题:

 'Click on the "Used Car Values" link Set AllHyperlinks = IE.document.getelementsbytagname("A") For Each hyper_link In AllHyperlinks If hyper_link.innertext = "Used Car Prices" Then hyper_link.Click Exit For End If Next 'Select model year" Set e = IE.document.getElementbyid("yearDropdown") '<-- error here if page not loaded per hyper_link.Click 

当你调用hyper_link.Click它会加载另一个页面(其中的下拉列表),然后按照Exit For下一个命令运行是Set e = IE...这将尝试和访问一个不存在的元素,因为该网页仍在加载每个hyper_link.Click 。 要解决这个问题,你可以像下面这样暂停:

 Application.Wait Now + TimeValue("0:00:04") 

这是一个黑客 – 有可能有更好的方法来解决它 – 但它可以让你设置下拉我的第一个build议:

完整的代码(重写你的):

 Option Explicit Sub WebForumEntry() Dim IE As Object Dim AllHyperLinks As Object Dim hyper_link As Object Dim e As Object Set IE = CreateObject("InternetExplorer.Application") IE.Top = 0 IE.Left = 0 IE.Width = 800 IE.Height = 600 IE.AddressBar = 0 IE.StatusBar = 0 IE.Toolbar = 0 IE.Navigate "http://www.kbb.com" IE.Visible = True ' wait for page to load Do DoEvents Loop Until IE.ReadyState = 4 'Click on the "Used Car Values" link Set AllHyperLinks = IE.document.getelementsbytagname("A") For Each hyper_link In AllHyperLinks If hyper_link.innertext = "Used Car Prices" Then hyper_link.Click Exit For End If Next 'wait 4 seconds - so page fully loads Application.Wait Now + TimeValue("0:00:04") 'Select model year" Set e = IE.document.getElementbyid("yearDropdown") ' set a year e.Value = "2016" End Sub 

…试着访问一个还不存在的元素,因为这个页面还在加载……只是暂停一下

太棒了,谢谢罗宾!