【发布时间】:2018-09-12 16:42:26
【问题描述】:
但此代码在打开两三个 URL 后停止,我们看到以下错误消息,
1.运行时错误91
2. 对象变量或块未设置
Sub test()
Dim wb As Object
Dim doc As Object
Dim sURL As String
Dim lastrow As Long
Dim n As Integer
Dim i As Integer
Dim HtmlToText As String
Dim result
lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To lastrow 'Start the loop on the second row of column A. Until the last URL..
Set wb = CreateObject("internetExplorer.Application")
sURL = Cells(i, 1)
wb.navigate sURL
wb.Visible = False
While wb.Busy
DoEvents
Wend
'HTML document
Set doc = wb.document
Dim Name As Variant
Dim Posts As Variant
Dim Followers As Variant
Dim Following As Variant
Dim DivValue As Variant
Dim DivValueSplit As Variant
Dim DivValueResult As Variant
Dim Biography As Variant
Name = doc.getElementsByClassName("AC5d8 notranslate")(0).innerText
Posts = doc.getElementsByClassName("g47SY")(0).innerText
Followers = doc.getElementsByClassName("g47SY")(1).innerText
Following = doc.getElementsByClassName("g47SY")(2).innerText
'dd = web.document.querySelector("div.-vDIg span").innerText
DivValue = doc.getElementsByClassName("-vDIg")(0).innerText
'DivValueSplit = Split(DivValue, "<br>")
'If UBound(DivValueSplit) = 2 Then
' DivValueResult = DivValueSplit(1) & DivValueSplit(2)
' j = InStr(DivValueResult, "</span>")
' Biography = Mid(DivValueResult, 7, j - 7)
'ElseIf sURL = "https://www.instagram.com/philipplein/" Then
' DivValueResult = DivValueSplit(0)
'j = InStr(DivValueResult, "</h1>")
'Biography = Mid(DivValueResult, 19, j - 5)
'Else
' DivValueResult = DivValueSplit(1)
' j = InStr(DivValueResult, "</span>")
' Biography = Mid(DivValueResult, 7, j - 7)
'End If
Worksheets("sheet1").Cells(i, 2) = Name
Worksheets("sheet1").Cells(i, 3) = Followers
Worksheets("sheet1").Cells(i, 4) = Following
Worksheets("sheet1").Cells(i, 5) = Posts
Worksheets("sheet1").Cells(i, 6) = DivValue
'Biography = Replace(re1, "<span>", "")
'Cells(i, 2) = HtmlToText
' myarray = Split(Data, vbCrLf)
err_clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
wb.Quit
Next i
End Sub
【问题讨论】:
-
那不是 VB.NET 代码。请查阅标签以了解正确用法。
-
不要使用
DoEvents来让你的程序在等待或做某事时响应。它可能会导致问题和意外错误 -
每次循环时,您都在创建和销毁 Internet Explorer 对象。不。创建一次并使用导航转到下一个 URL,即在循环之前创建 Internet Explorer 对象并在之后退出。
标签: html vba excel web-scraping