【问题标题】:Scraping the Business name using Web class="search-item-header"使用 Web class=\"search-item-header\" 抓取企业名称
【发布时间】:2022-08-14 04:07:40
【问题描述】:

我正在尝试提取公司名称从一个网站。

我收到一个错误。
e]1

For iCnt = 0 To .getElementsByTagName(\"h2\").Length - 1

我需要提取网站上提供的所有详细信息,例如:

Business Name
Address
Telephone
Fax
Email
Website

按顺序排列,以便所有详细信息都可以粘贴到 Excel 文件中。

Option Explicit

Const sSiteName = \"https://www.thoroughexamination.org/postcode-search/nationwide?page=1\"

Private Sub getHTMLContents()
    \' Create Internet Explorer object.
    Dim IE As Object
    Set IE = CreateObject(\"InternetExplorer.Application\")
    IE.Visible = False          \' Keep this hidden.
    
    IE.Navigate sSiteName
    
    \' Wait till IE is fully loaded.
    While IE.ReadyState <> 4
        DoEvents
    Wend
    
    Dim oHDoc As HTMLDocument     \' Create document object.
    Set oHDoc = IE.Document
    
    Dim oHEle As HTMLUListElement     \' Create HTML element (<ul>) object.
    Set oHEle = oHDoc.getElementById(\"search-item-header\")   \' Get the element reference using its ID.
    
    Dim iCnt As Integer
    
    \' Loop through elements inside the <ul> element and find <h1>, which has the texts we want.
    With oHEle
        For iCnt = 0 To .getElementsByTagName(\"h2\").Length - 1
            Debug.Print .getElementsByTagName(\"h2\").Item(iCnt).getElementsByTagName(\"a\").Item(0).innerHTML
        Next iCnt
    End With
    
    \' Clean up.
    IE.Quit
    Set IE = Nothing
    Set oHEle = Nothing
    Set oHDoc = Nothing
End Sub

第二个代码没有响应:

Sub TutorailsPoint()
Const URL = \"https://www.thoroughexamination.org/postcode-search/nationwide?page=1\"
Dim http As New MSXML2.XMLHTTP60, html As New HTMLDocument
Dim topics As Object, posts As Object, topic As Object
Dim x As Long

x = 1

http.Open \"GET\", URL, False
http.send
html.body.innerHTML = http.responseText

Set topics = html.getElementsByClassName(\"search-item-header\")
For Each posts In topics
    For Each topic In posts.getElementsByTagName(\"h2\")
        Cells(x, 1) = topic.innerText
        x = x + 1
    Next topic
Next posts
End Sub

    标签: excel vba web-scraping


    【解决方案1】:

    如果你使用 UserAgent,你可以用 xhr 做你想做的事。这是每行所有数据集的代码,其中包含您发布的网址的所有页面的当前字段。

    Sub TutorailsPoint()
      Dim doc As Object
      Dim url As String
      Dim page As Long
      Dim hits As Long
      Dim maxPage As Long
      Dim maxPageKnown As Boolean
      Dim currRow As Long
      Dim nodeAllGroups As Object
      Dim nodeOneGroup As Object
      Dim nodeContactData As Object
      Dim nodeWebSite As Object
      Dim telephone As Boolean
      
      page = 1
      maxPage = 1
      currRow = 2
      Set doc = CreateObject("htmlFile")
      With CreateObject("MSXML2.ServerXMLHTTP.6.0")
        'Call all pages
        Do
          url = "https://www.thoroughexamination.org/postcode-search/nationwide?page=" & page
          .Open "GET", url, False
          .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0"
          .send
          
          If .Status = 200 Then
            doc.body.innerHTML = .responseText
            
            'How many pages to call
            If Not maxPageKnown Then
              hits = CLng(doc.getElementsByClassName("summary")(0).getElementsByTagName("b")(1).innertext)
              maxPage = hits / 20
              If hits Mod 20 <> 0 Then
                maxPage = maxPage + 1
              End If
              maxPageKnown = True
              'Debug.Print maxPage
            End If
            
            Set nodeAllGroups = doc.getElementsByClassName("group")
            For Each nodeOneGroup In nodeAllGroups
              'Business name
              Cells(currRow, 1) = nodeOneGroup.getElementsByTagName("h2")(0).innertext
              'Address
              Cells(currRow, 2) = nodeOneGroup.getElementsByTagName("p")(0).innertext
              
              'Contact block
              Set nodeContactData = nodeOneGroup.getElementsByClassName("depot")
              If nodeContactData.Length <> 0 Then
                'Telephone
                If InStr(1, nodeContactData(0).innertext, "tel:") > 0 Then
                  Cells(currRow, 3).NumberFormat = "@"
                  Cells(currRow, 3) = Trim(nodeContactData(0).getElementsByTagName("strong")(0).innertext)
                  telephone = True
                End If
                
                'Fax
                If InStr(1, nodeContactData(0).innertext, "fax:") > 0 Then
                  Cells(currRow, 4).NumberFormat = "@"
                  If telephone Then
                    Cells(currRow, 4) = Trim(Replace(nodeContactData(0).getElementsByTagName("p")(0).FirstChild.NextSibling.NextSibling.NextSibling.NodeValue, "fax:", ""))
                  Else
                    Cells(currRow, 4) = Trim(Replace(nodeContactData(0).getElementsByTagName("p")(0).FirstChild.NodeValue, "fax:", "")) 'not sure, not seen no telephone
                  End If
                End If
                
                'Email
                If InStr(1, nodeContactData(0).innertext, "email:") > 0 Then
                  Cells(currRow, 5) = Trim(nodeContactData(0).getElementsByTagName("a")(0).innertext)
                End If
                
                'website
                Set nodeWebSite = nodeContactData(0).getElementsByClassName("website")
                If nodeWebSite.Length > 0 Then
                  Cells(currRow, 6) = Trim(nodeWebSite(0).innertext)
                End If
              End If
              
              telephone = False
              currRow = currRow + 1
            Next nodeOneGroup
            
            page = page + 1
          Else
            Cells(currRow, 1) = "Page not loaded. HTTP status " & .Status
            Cells(currRow, 2) = url
            currRow = currRow + 1
          End If
        Loop While page <= maxPage
      End With
    End Sub
    

    【讨论】:

    • 非常感谢您,如果您可以在代码中添加更多 cmets 以便我学习它,我将不胜感激。 @Zwenn
    【解决方案2】:

    Internet Explorer 已被 MS 删除,因此使用它不是一个好主意。从现在开始,在 VBA 中,我最好的选择是使用 Selenium(Selenium 类型库)来抓取 WWW。要以正确的方式开始使用 Selenium,您必须注意以下事项:

    1. 更新相关的 .Net 框架

    2. 安装Selenium Basic 应用

    3. 下载安装Chromedriver.exe版本(查看最新版本here)与谷歌浏览器版本完全兼容(本机必须安装)。提取“Chromedriver.exe”并将其放在安装 Selenium Basic 的同一文件夹中(我在这里安装了 Selenium Basic:“C:\Program Files\SeleniumBasic”)

    4. 将 VBE 中的引用添加到 ActiveX 库:'Selenium Type Library'

      将代码放在 VBE 上的标准模块中:

      Sub fnGetDataFromWWW()
          Dim oWD As WebDriver
          Dim post As Selenium.WebElement
          Dim groups As Selenium.WebElements
          Dim strText As String
          Dim intItem As Integer
      
          Set oWD = New Selenium.WebDriver
          oWD.Start "chrome"
          DoEvents
          oWD.Get "https://www.thoroughexamination.org/postcode-search/nationwide?page=1"
          DoEvents
      
          Set groups = oWD.FindElementsByClass("group")
          
          For Each post In groups
              strText = post.Attribute("outerText")
              For intItem = 0 To UBound(Split(strText, Chr(10)))
                  If Trim(Split(strText, Chr(10))(intItem)) <> "" Then
                      Debug.Print Split(strText, Chr(10))(intItem)
                  End If
              Next
          Next post
      
      End Sub
      

    【讨论】:

    • 非常感谢您,我也会尝试学习 Selenium Basic。如果您可以分享任何网站以从头开始学习,我将不胜感激。
    • 试试看。您必须通过访问各种网站来学习。 Stack Overflow 的答案中有一些很好的材料。 Selenium Basic 的创建者以代号 FlorentBr (github.com/florentbr/SeleniumBasic) 参与其中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 2017-10-14
    • 1970-01-01
    • 2014-11-25
    • 2011-05-05
    • 2018-04-29
    • 2012-12-11
    相关资源
    最近更新 更多