【发布时间】:2018-02-15 11:08:33
【问题描述】:
我创建了一个宏来使用 TagName 抓取零售商网站的价格,这确实有效,但是一旦 TagName 移动位置,我就必须重新定位并更改位置编号。
我目前正在使用 IF 函数在目标价格方面对冲我的赌注。理想情况下,我需要使用 Class 或 ID 来恢复价格,但我多次尝试都失败了。
网站: https://www.usc.co.uk/puma-roma-basic-perforated-trainers-023210?colcode=02321069
样式 023210/69(前 6 位 = sName)(后 2 位 = SCOL)
任何帮助将不胜感激!以下是我当前的代码
Sub browse()
Do Until IsEmpty(ActiveCell)
Dim sPath As String, sPathEnd As String, sName As String, SCOL As String
sName = ActiveCell.Value
SCOL = ActiveCell.Offset(0, 1)
Dim IE As New SHDocVw.InternetExplorer
IE.Visible = False
IE.navigate "https://www.usc.co.uk/" & sName & "?colcode=" & SCOL & ""
Do While IE.ReadyState <> READYSTATE_COMPLETE
Loop
''Debug.Print IE.LocationName, IE.LocationURL
Dim doc As HTMLDocument
Set doc = IE.Document
Dim SellingPrice As String
Dim OriginalPrice As String
Dim SellingPrice2 As String
Dim OriginalPrice2 As String
SellingPrice = Trim(doc.getElementsByTagName("SPAN")(154).innerText)
OriginalPrice = Trim(doc.getElementsByTagName("SPAN")(155).innerText)
SellingPrice2 = Trim(doc.getElementsByTagName("SPAN")(111).innerText)
OriginalPrice2 = Trim(doc.getElementsByTagName("SPAN")(112).innerText)
If SellingPrice = "Add to bag" Then
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = SellingPrice2
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = OriginalPrice2
ActiveCell.Offset(1, -3).Select
Else
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = SellingPrice
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = OriginalPrice
ActiveCell.Offset(1, -3).Select
End If
Loop
Cells.Select
Cells.EntireColumn.AutoFit
End Sub
【问题讨论】:
-
如果我考虑您粘贴在顶部的 URL,您的预期输出是什么?
-
您应该循环所有元素以确保获得正确的元素。检查HtmlElement.GetAttribute。例如,如果
class=productHasRef,您可以循环所有跨度并确保获得正确的跨度,或者可以按 ID 选择 div,然后获取 Innertext。
标签: vba excel web-scraping screen-scraping