2016-08-25 161 views
-1

我是VBA和html编码的新手。如果我不了解基本术语或错误地使用它们,我很抱歉。我期待在excel中创建和运行一个宏,这样可以使我的工作变得更容易。从本质上讲,我需要从一个房地产网站上获取大量信息。这包括地址,标价,上市代理,拍卖日期(如果有的话)等。我花了最近4个小时阅读所有关于网页抓取的内容,我理解这些流程,我只是不知道如何编码。根据我读过的内容,我需要编写一个代码来自动打开网站,强制等待直到它被加载,然后通过标记,名称或ID检索信息。它是否正确?我怎么去解决这个问题。我应该使用哪些资源。如何从网站上抓取信息?

TL; DR如何从网页上刮取搜索结果网页中的文本(noob指令)。

回答

0

我不会告诉你所有的细节,你必须自己找到它们。有些网页很复杂,有些很容易。其他是不可能的,特别是如果文本不是以HTML格式显示,而是以其他形式显示 - 图片,Flash等。

但是,在Excel中从HTML网页提取数据非常简单。首先,你想自动化它。因此点击'开发人员'功能区上的'录制宏'。这样,您将记录所有可重复的步骤,然后您可以查看宏,并根据需要调整某些步骤。然而,我不能在这里教你如何编程VBA。

当您录制宏时,点击'数据'功能区上的'从网络'。这将显示一个新的网络查询。然后输入您想要阅读的网页地址,然后尝试选择(尽量使用小箭头或注销标记)作为您感兴趣的狭窄区域。您也可以在此向导对话框中浏览一些微调选项。

完成后,单击“导入”,您将以某种形式显示网页的内容。如果你幸运的话,你感兴趣的数据将永远在同一个单元格中。然后,您可以读取单元格并将值存储在某处(可能使用另一个宏)。如果每次刷新查询时数据不在同一个单元格中,那么运气不好,必须使用一些复杂的公式或宏来查找它们。

下一步停止正在记录的宏,并查看记录的代码。试着去尝试一下,直到你发现你真正需要的东西。那么它取决于你,你想如何自动化它。选项很多...

否则Excel可能不是最好的工具。如果我想加载HTML页面并从中提取数据,我会使用一些脚本例如Python比Excel和VBA具有更好的工具。还有一些工具可以将HTML转换为XHTML,然后从格式良好的XML中提取数据。

0

下面是一个非常基本的例子,说明了一些网络抓取的概念。其他阅读你应该做的,将是如何使用其他元素选择器,如getElementByIDgetElementByClassNamegetElementByName

这里有一些代码让你开始。

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