【发布时间】:2018-10-05 04:37:42
【问题描述】:
我正在处理以前处理过的问题,但不是在这种情况下。
我正在使用 VBA 从 USPS 网站提取地址。当我在我的单元格“ele.innertext”中放置类中的 all 内部文本时,但 VBA 不会让我将内部文本隔离到项目级别 - ele.item(1)。例如,innertext 给我上面的错误。你知道为什么吗?
我的浏览器是 IE11。
相关 HTML:
<div id="zipByAddressDiv" class="industry-detail">Loading...</div>
<!-- start Handlebars template -->
<script id="zipByAddressTemplate" type="text/x-handlebars-template">
<ul class="list-group industry-detail">
{{#each addressList}}
<li class="list-group-item paginate">
<div class="zipcode-result-address">
<p>{{companyName}}</p>
<p>{{addressLine1}}</p>
<p>{{city}} {{state}} <strong>{{zip5}}-{{zip4}}</strong></p>
VBA:
Sub USPS()
Dim eRow As Long
Dim ele As Object
Dim objie As Object
Dim wscript As Object
Dim test As String
Dim testarray() As String
'Dim goods As Object
Dim r As Integer
Dim x As Long: x = 0
Dim vFacility As Variant
Dim y As Variant
'Dim IE As New InternetExplorer
Sheets("Address").Select
eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Set objie = CreateObject("InternetExplorer.Application")
For r = 4 To 8
myaddress = Cells(r, 5).Value
mycity = Cells(r, 7).Value
mystate = Cells(r, 8).Value
myzipcode = Cells(r, 9).Value
'myaddress = Range("a2").Value
'mycity = Range("c2").Value
'mystate = Range("d2").Value
'myzipcode = Range("e2").Value
With objie
.Visible = True
.navigate "https://tools.usps.com/go/ZipLookupAction!input.action"
Do While .Busy
DoEvents
Loop
Set what = .document.getElementsByName("tAddress")
what.Item(0).Value = myaddress
Set zipcode = .document.getElementsByName("tCity")
zipcode.Item(0).Value = mycity
Set zipcode1 = .document.getElementsByName("tState")
zipcode1.Item(0).Value = mystate
Set zipcode2 = .document.getElementsByName("tZip-byaddress")
zipcode2.Item(0).Value = myzipcode
.document.getElementByID("zip-by-address").Click
Do While .Busy
DoEvents
Loop
For Each ele In .document.all
Select Case ele.className
Case "industry-detail"
test = ele.innertext
testarray = Split(test, vbCrLf)
Worksheets("Address").Cells(r, 11).Value = testarray(4)
'Debug.Print test
'Debug.Print "and"
'Debug.Print testarray(4)
End Select
Next ele
End With
Next r
Set objie = Nothing
Set ele = Nothing
Set IE = Nothing
'IE.Quit
End Sub
【问题讨论】:
-
很好地使用 VBA 进行网页抓取。你得到什么错误,在哪一行?能否也包含更多的 VBA 代码?
-
@alexM 谢谢!我不能把大部分归功于它。我已经包含了所有的 VBA(其中包括许多不必要的正在进行的工作)。错误出现在 cell = ele.item(1).innertext 处。然而,我做了一个解决方法,将所有内部文本放入一个字符串,根据分页符将该字符串拆分为一个数组,然后单独使用正确的“行”。感谢您的关注!
-
为什么要抓取页面?他们有a web API。
标签: excel vba web-scraping usps