【问题标题】:Scraping the source code using VBA-Macros使用 VBA-Macros 抓取源代码
【发布时间】:2018-07-25 19:55:54
【问题描述】:

我需要从比价网站(产品链接:https://www.toppreise.ch/prod_488002.html)抓取价格值。我不能刮。查看我要捕获的图像中突出显示的价格:

请帮助我如何抓取此页面。

PS:toppreise.ch 在许多国家/地区无法访问,因此请使用 VPN

我正在使用以下代码:

Private Sub SiteInfo_Click()
Dim strhtml
On Error Resume Next
ThisWorkbook.Sheets("Data Mining").Activate
Sheets("Data Mining").Range("B1").Select
Set xmlHttp = Nothing
Set xmlHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")

    StrUrl = ""
    StrUrl = Sheets("Data Mining").Range("B1").Value
    xmlHttp.Open "GET", StrUrl, False
    xmlHttp.Send
    strhtml =xmlHttp.responseText
    END Sub

当我在上面运行代码时,我只得到下面的响应文本。它没有给出整个页面。 (您可以通过产品链接查看源代码或查看这里https://www.dropbox.com/s/ah80jt7a25xcicp/source%20code.txt?dl=0

<html><head>
        <script type="text/javascript" src="//en.toppreise.ch/js/tpjs.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/afxp.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/jquery.min.js"></script>
        <script type="text/javascript" src="//en.toppreise.ch/js/jquery-ui-autocomplete.min.js"></script>
    </head><body>...   

【问题讨论】:

  • 看起来页面是动态的,因此您必须使用不同的方法,例如浏览器自动化。
  • 非常感谢@TimWilliams。你能帮忙吗? BTW 如何判断页面是否动态?
  • 记得用 On Error GoTo 0 关闭 On Error Resume Next(尽快)。否则你会一直隐藏错误。
  • 尝试谷歌搜索“VBA 自动化 IE”,你会得到很多例子。

标签: vba excel web-scraping web-crawler


【解决方案1】:

此代码有效,感谢 SIM

Sub Get_Price()
Dim HTTP As New XMLHTTP60, HTML As New HTMLDocument
Dim post As HTMLDivElement

With HTTP
.Open "GET", "https://www.toppreise.ch/index.php?a=488002", False
.send
HTML.body.innerHTML = .responseText
End With

For Each post In HTML.getElementsByClassName("altLinesOdd")
With post.getElementsByTagName("a")
     If .Length Then R = R + 1: Cells(R, 1) = .Item(0).innerText
End With
With post.getElementsByClassName("spaceVert nobreak")
     If .Length Then Cells(R, 2) = .Item(0).innerText
End With
Next post
End Sub

【讨论】:

  • 欢迎来到 Stack Overflow!感谢您提供此代码 sn-p,它可能会提供一些有限的短期帮助。一个正确的解释would greatly improve 它的长期价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
猜你喜欢
  • 1970-01-01
  • 2013-05-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2017-12-23
  • 2021-10-10
  • 1970-01-01
  • 2014-08-19
相关资源
最近更新 更多