2017-07-28 91 views
0

使用下面的腳本,我成功地返回從HTML表中的值到從下面的鏈接工作簿:link1link2。但是,當我試圖對以下link3使用相同的腳本時,它不會返回任何內容。我認爲這是由於網站上存在複雜的HTML表格結構。我相信代碼需要.Item(0)號碼由於表格的複雜性而需要調整,請指教。刮HTML表格使用VBA

Sub Web_Data() 
    Dim http As New XMLHTTP60, html As New HTMLDocument 
    Dim topic As HTMLHtmlElement 

    With http 
     .Open "GET", "http://www.dolphinfitness.co.uk/en/optimum-nutrition/", False 
     .send 
     html.body.innerHTML = .responseText 
    End With 

    For Each topic In html.getElementsByClassName("category-products") 
     With topic.getElementsByClassName("product-name") 
      If .Length Then x = x + 1: Cells(x, 1) = .Item(0).innerText 
     End With 
     With topic.getElementsByClassName("price") 
      If .Length Then Cells(x, 2) = .Item(0).innerText 
     End With 
    Next topic 
End Sub 
+0

可否請你彌補劇本,我會下載硒。 – Martin

+0

我需要安裝哪個版本才能完成這項工作? [selenium下載頁面](http://www.seleniumhq.org/download/) – Martin

+0

順便說一句,我看到我的評論看到你的腳本中的鏈接。這是你需要刮的鏈接嗎? – SIM

回答

1

您在文章中提到的網站在分析不同產品的價格時有點棘手。很少有產品已經獲得原價,其餘的都有特價。你不能一次解析它們兩個,直到你應用表達式的技巧。我寫了一個能夠處理它們的xpath,你將能夠獲得它們。這裏是腳本:

Sub Body_Building() 
    Dim driver As New WebDriver, post As Object 

    With driver 
     .Start "chrome", "http://www.bodybuildingwarehouse.co.uk" 
     .Get "/optimum-nutrition?limit=all" 
    End With 

    On Error Resume Next 
    For Each post In driver.FindElementsByClass("grid-info") 
     i = i + 1: Cells(i, 1) = post.FindElementByClass("product-name").Text 
     Cells(i, 2) = post.FindElementByXPath(".//span[@class='regular-price']//span[@class='price']|.//p[@class='special-price']//span[@class='price']").Text 
    Next post 
End Sub 

讓我知道如果你有任何問題執行腳本。順便說一句,硒綁定與VBA沒有任何財產迴避「在錯誤恢復下一步」,所以我把它放在循環之前。謝謝。

+0

好吧,我已經知道它是如何完成的。但是當我試圖運行上面的VBA時突然出現以下錯誤:**驅動程序爲新的ChromeDriver **,錯誤本身:*​​用戶定義的類型未定義**。 – Martin

+0

我腦海中有兩件事情可以看到。 1.你安裝了chromedriver嗎? 2.是否在執行前在參考庫中添加了「硒類型庫」?順便說一句,網頁抓取將非常舒服,如果你知道如何使用硒原因,現在你將面對大量的JavaScript注入網站。 – SIM

+0

對不起,我很困擾你,但這對我來說是全新的東西。我發現了以下錯誤:[imgur(http://imgur.com/a/DHCvS),所以下面的說明[此鏈接(因爲我已經安裝了ChromeDrivers我已經加入硒庫引用https://開頭www.youtube.com/watch?v=dz59GsdvUF8) – Martin