我对 VBA 和 html 编码总体来说是新手。如果我不理解基本术语或错误使用它们,我深表歉意。我希望在 Excel 中创建并运行一个宏,这将使我的工作变得更加轻松。本质上,我需要从房地产网站获取大量信息。这包括地址、标价、挂牌机构、拍卖日期(如果有)等。我花了 4 个小时阅读有关网络抓取的所有内容,我了解整个流程,只是不知道如何编写代码。根据我所读到的内容,我需要编写一段代码来自动打开网站,强制等待网站加载,然后通过标签、名称或 ID 检索信息。它是否正确?我该怎么办呢。我应该使用哪些资源。
TL;DR 如何从搜索结果网页中抓取文本(新手说明)。
我不会告诉你所有细节,你必须自己找到它们。有些网页很复杂,有些则很简单。其他都是不可能的,特别是如果文本不是以 HTML 形式显示而是以其他形式(图片、Flash 等)显示。
然而,在 Excel 中从 HTML 网页中提取数据非常简单。首先,您想要自动化它。因此,单击“开发人员”功能区上的“录制宏”。这样,您将记录所有可重现的步骤,然后您可以查看宏并调整一些步骤以满足您的需求。然而我不能在这里教你如何编程 VBA。
录制宏时,单击“数据”功能区上的“来自网络”。这将显示一个新的网络查询。然后,您输入要阅读的网页地址,并尝试选择(使用小箭头或复选标记)您感兴趣的尽可能窄的区域。您还可以在此向导对话框中探索一些微调选项。
完成后,单击“导入”,您将以某种形式获得网页内容。如果幸运的话,您感兴趣的数据将始终位于相同的单元格中。然后您可以读取单元格并将值存储在某处(可以使用另一个宏)。如果每次刷新查询时数据都不在同一单元格中,那么您运气不好,必须使用一些复杂的公式或宏来查找它们。
接下来停止您正在录制的宏并查看录制的代码。尝试尝试并使用它,直到发现您真正需要的东西。然后由您决定如何实现自动化。选择很多...
否则 Excel 可能不是最好的工具。如果我想加载 HTML 页面并从中提取数据,我会使用一些脚本,例如Python 拥有比 Excel 和 VBA 更好的工具。还有一些工具可以将 HTML 转换为 XHTML,然后从中提取数据,就像从格式正确的 XML 中提取数据一样。
下面是一个非常基本的示例,说明了网络抓取的一些概念。您应该做的其他阅读是如何使用其他元素选择器,例如
getElementByID
getElementByClassName
getElementByName
。
这里有一些代码可以帮助您入门。
Public Sub ExampleWebScraper()
Dim Browser As Object: Set Browser = CreateObject("InternetExplorer.Application")
Dim Elements As Object 'Will hold all the elements in a collection
Dim Element As Object 'Our iterator that will show us the properties
'Open a page and wait for it to load
With Browser
.Visible = True
.Navigate "www.google.com"
'Wait for the page to load
While .busy Or .readystate <> 4
Application.Wait (Now() + TimeValue("00:00:01"))
Wend
'Enumerate all Elements on the page
'It will store these elements into a collection which we can
'iterate over. The * is the key for ALL, here you can specify
'any tagName and it will limit your search to just those.
'E.g. the most common is Likely Input
Set Elements = .document.getElementsByTagname("*") ' All elements
'Iterate through all elements, and print out some properties
For Each Element In Elements
On Error Resume Next ' This is needed as not all elements have the properties below
' if you try and return a property that doesn't exist for that element
' you will receive an error
'The following information will be output to the 'Immediate Window'
'If you don't see this window, Press Ctrl+G, and it will pop up. That's where this info will display
Debug.Print "The Inner Text is: " & Element.InnerText
Debug.Print "The Value is: " & Element.Value
Debug.Print "The Name is: " & Element.Name
Debug.Print "The ID is: " & Element.ID
Debug.Print "The ClassName is: " & Element.Class
Next Element
End With
'Clean up, free memory
Set Browser = Nothing
Set Elements = Nothing
Set Element = Nothing
End Sub