簡體   English   中英

需要幫助與Excel VBA刮

[英]need help scraping with excel vba

我需要抓取標題,產品說明和產品代碼,並將其從<<< HERE >>>保存到工作表中,在這種情況下,這些是:

  1. “凱瑟琳蘭斯菲爾德海倫娜多床罩-雙”
  2. “這款令人驚嘆的象牙色床罩經過特別設計,可與Helena卧室系列一起使用。它具有微妙的花卉設計,帶有菱形finish縫飾面。床罩帶有襯墊,因此可以在夏天用作輕質被子或額外的層滌綸,尺寸L260,寬240厘米,適合雙人床使用,可在30°C機洗,適用於滾筒烘干EAN:5055184924746。
  3. 產品代碼116/4196“

我嘗試了不同的方法,但最后沒有一個方法對我有好處。 對於Mid和InStr函數,結果為空,可能是我的代碼錯誤。 抱歉,我沒有提供任何代碼,因為我已經把它弄亂了很多次,也沒有結果。 我試圖用GetDatafromPage抓取孔頁。 它運作良好,但是對於不同的產品頁面,隨着元素數量在頁面之間的變化,輸出將轉到不同的行。 而且,不可能只刮取選定的元素。 因此,從定義的單元中獲取價值是沒有意義的。

替代使用InternetExplorer對象的另一個選項是xmlhttp對象。 這是與kekusemau相似的示例,但是使用xmlhttp對象來請求頁面。 然后,我從html文件中的xmlhttp對象加載responseText

Sub test()
    Dim xml As Object
    Set xml = CreateObject("MSXML2.XMLHTTP")
    xml.Open "Get", "http://www.argos.co.uk/static/Product/partNumber/1164196.htm", False
    xml.send

    Dim doc As Object
    Set doc = CreateObject("htmlfile")
    doc.body.innerhtml = xml.responsetext

    Dim name
    Set name = doc.getElementById("pdpProduct").getElementsByTagName("h1")(0)
    MsgBox name.innerText

    Dim desc
    Set desc = doc.getElementById("genericESpot_pdp_proddesc2colleft").getElementsByTagName("div")(0)
    MsgBox desc.innerText

    Dim id
    Set id = doc.getElementById("pdpProduct").getElementsByTagName("span")(0).getElementsByTagName("span")(2)
    MsgBox id.innerText
End Sub

這似乎不太困難。 您可以使用Firefox來查看頁面結構(右鍵單擊某處,然后單擊inspect element ,然后從那里繼續...)

這是一個簡單的示例代碼:

Sub test()
    Dim ie As InternetExplorer
    Dim x

    Set ie = New InternetExplorer
    ie.Visible = True
    ie.Navigate "http://www.argos.co.uk/static/Product/partNumber/1164196.htm"
    While ie.ReadyState <> READYSTATE_COMPLETE
        DoEvents
    Wend

    Set x = ie.Document.getElementById("pdpProduct").getElementsByTagName("h1")(0)
    MsgBox Trim(x.innerText)

    Set x = ie.Document.getElementById("genericESpot_pdp_proddesc2colleft").getElementsByTagName("div")(0)
    MsgBox x.innerText

    Set x = ie.Document.getElementById("pdpProduct").getElementsByTagName("span")(0).getElementsByTagName("span")(2)
    MsgBox x.innerText

    ie.Quit
End Sub

(我在Excel中有對Microsoft Internet Controls的引用,我不知道默認情況下是否存在該引用,如果沒有,則必須先設置它才能運行此代碼)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM