如何让我的VBA刮刀find上面的行?

我有一些与VBA的经验,但我很新,用VBA的网页抓取。 然而,我非常热心,想到了1000种方法,我怎么能使用它,使我的工作更容易。 🙂

我的问题是,我有一个网站有两个input字段和一个button。 我可以写在input字段(他们有ID,所以我可以很容易地find他们)我的input字段的代码:

.Document.getElementById("header_keyword").Value = my_first .Document.getElementById("header_location").Value = my_last 

但我真的坚持点击button。

这里是button的html代码:

 <span class="p2_button_outer p2_button_outer_big"><input class="p2_button_inner" type="submit" value="Keresés" /></span> <span class="p2_button_outer p2_button_outer_big light hide_floating"><a id="tour_det_search" class="p2_button_inner" href="http://www.profession.hu/kereses">Részletes keresés</a></span> 

正如你所看到的,彼此靠近有两个不同的button,他们共享同一个class级。 我正在寻找第一/上一个。 我的问题是,它没有ID,只有类,types和价值。 但我没有findgetelementsbytype或getelementsbyvalue方法。 有没有解决scheme来findbuttontypes或值(或两者)?

对不起,如果我问一些愚蠢的,但正如我刚才所说,我是在刮新… :)预先感谢您,并有一个愉快的周末!

您可以使用以下function。 它会查找具有给定标题的第一个HTML元素。 您也可以通过HTML标签来限制search。 (该代码与IE <9不兼容getElementsByClassName方法)兼容。

 Public Function FindElementByCaption(dom As Object, Caption As String, _ Optional Tag As String, Optional Nested As Boolean = True) As Object Dim ControlsSet As Variant Dim Controls As Variant Dim Control As Object '------------------------------------------------------------------------------------ Set ControlsSet = VBA.IIf(Nested, dom.all, dom.childNodes) If VBA.Len(Tag) Then Set Controls = ControlsSet.tags(VBA.LCase(Tag)) Else Set Controls = ControlsSet End If For Each Control In Controls If VBA.StrComp(Control.InnerHtml, Caption, vbTextCompare) = 0 Then Set FindElementByCaption = Control Exit For End If Next Control End Function 

以下是如何在您的代码中应用它:

 Dim button As Object Set button = FindElementByCaption(.Document, "Keresés", "INPUT", True) If Not button Is Nothing Then Call button.Click Else Call MsgBox("Button has not been found") End If 

幸运的是我已经制定出解决scheme。 🙂

我做的是以下。 我search了相关的类,然后使用getAttribute()方法循环遍历我search特定值的类,并在find它时单击它。

以下是工作代码:

 Set my_classes = .Document.getElementsByClassName("p2_button_inner") For Each class In my_classes If class.getAttribute("value") = "Keresés" Then Range("c4") = "Clicked" class.Click Exit For End If Next class 

谢谢!