VBA从隐藏字段中抓取值

时间:2018-11-02 23:41:01

标签: html excel vba web-scraping scrape

我对抓取HTML还是陌生的,现在已经尝试了几天,使用类名和ID从隐藏字段中抓取值,但是我仍然无法获取该值。

我正在尝试从以下HTML获取值(4);

<input id="collectionQuantity" type="hidden" value="4">

这是从下面较大的摘录中提取的;

<div class="lg-24 md-12 cols">
					
	<input id="selectedBranchCode" type="hidden" value="OT4">
	<input id="selectedBranchName" type="hidden" value="Ashton-under-Lyne">
	<input id="collectionQuantity" type="hidden" value="4">
						
		<button id="add_for_collection_button_3730P" title="Click here to add this item to your basket for collection" class="btn btn--lg btn--col fill " data-content="add-to-basket">Click &amp; Collect</button>
		<p id="branch_collection_3730P">4 in stock in <strong>Ashton-under-Lyne</strong> <a href="https://www.screwfix.com/jsp/cpc/cpcCheckStock.jsp?product_id=3730P" id="click_and_collect_3730P" class="_btn--link">Change store</a></p>
													
				</div>

我尝试了许多获得价值的方法。 我认为我最亲近的是;

sh01.Cells(r, 5) = HTML.getElementsByClassName("lg-24 md-12 cols")(3).innertext                                  'product stock
sh01.Cells(r, 5) = HTML.getElementsByTagName("p")(7).innertext                                                   'product stock
sh01.Cells(r, 5) = HTML.getElementById("branch_collection_" & z_sh01.Cells(y, 2)).innertext                      'product stock
sh01.Cells(r, 5) = HTML.getElementsByClassName("lg-24 md-12 cols")(3).getElementById("collectionQuantity").Value 'product stock
sh01.Cells(r, 5) = HTML.querySelector("# branch_collection_" & z_sh01.Cells(y, 2)).innertext                     'product stock
sh01.Cells(r, 5) = HTML.getElementById("collectionQuantity").innertext                                           'product stock

预先感谢您的帮助。

伊恩

1 个答案:

答案 0 :(得分:0)

尝试

HTML.querySelector("#collectionQuantity").Value

HTML.getElementById("collectionQuantity").getAttribute("value")

甚至

HTML.getElementById("collectionQuantity").Value

您追求的是目标元素的value属性值而不是.innerText。上面显示了3种方法。


因此,我必须先设置一个本地存储,然后再添加一个不同的导航,以确保在转到感兴趣的页面之前已设置了本地存储,否则该存储将留空,因此相关元素的.value还是空白

Option Explicit

Public Sub GetInfo()
    Dim IE As New InternetExplorer
    With IE
        .Visible = True
        .Navigate2 "https://www.screwfix.com/jsp/tradeCounter/tradeCounterDetailsPage.jsp?id=460"

        While .Busy Or .readyState < 4: DoEvents: Wend

        .document.querySelector("input.btn").Click

        While .Busy Or .readyState < 4: DoEvents: Wend
        .Navigate2 "https://www.screwfix.com/p/hd907-9q-freestanding-oil-filled-radiator-2000w/3730p"

        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document

            Debug.Print .getElementById("collectionQuantity").Value

        End With

        .Quit
    End With
End Sub