Как вычистить класс и, если не найден, вычистить другой - PullRequest
0 голосов
/ 09 марта 2020

Я использую VBA для чистки сайта. Сделанный мной скребок работает, но я хочу реализовать еще 2 функции и не знаю, как это сделать. Это код:

Sub pronutrition()
Set ie = CreateObject("InternetExplorer.Application")
my_url = "https://www.myprotein.ro/"
ie.Visible = True
i = 20
LastRow = ActiveSheet.Range("A" & ActiveSheet.Rows.Count).End(xlUp).Row

Set Rng = ActiveSheet.Range("A20:A" & LastRow)
For Each cell In Rng

ie.navigate my_url
    Do While ie.Busy
        DoEvents
    Loop
    Wait 1

ie.Document.getElementsByName("search")(0).Value = cell


ie.Document.getElementsByClassName("headerSearch_button")(0).Click
    Do While ie.Busy
        DoEvents
    Loop
    Wait 2
ActiveSheet.Range("B" & i) = ie.Document.getElementsByClassName("athenaProductBlock_productName")(0).innerText + ie.Document.getElementsByClassName("athenaProductBlock_fromValue")(0).innerText
    Do While ie.Busy
        DoEvents
    Loop
    Wait 2

ActiveSheet.Range("C" & i) = ie.Document.getElementsByClassName("athenaProductBlock_productName")(1).innerText + ie.Document.getElementsByClassName("athenaProductBlock_fromValue")(1).innerText
    Do While ie.Busy
        DoEvents
    Loop
    Wait 2

ActiveSheet.Range("D" & i) = ie.Document.getElementsByClassName("athenaProductBlock_productName")(2).innerText '+ ie.Document.getElementsByClassName("athenaProductBlock_priceValue")(2).innerText
    Do While ie.Busy
        DoEvents
    Loop
    Wait 2

ActiveSheet.Range("E" & i) = ie.Document.getElementsByClassName("athenaProductBlock_productName")(3).innerText '+ ie.Document.getElementsByClassName("athenaProductBlock_priceValue")(3).innerText

    Do While ie.Busy
        DoEvents
    Loop
    Wait 2

i = i + 1
Next cell
ie.Quit
MsgBox "Done"
End Sub

Сначала я хочу найти класс "athenaProductBlock_fromValue", а если он не найдет его, искать "athenaProductBlock_priceValue", и, во-вторых, если он не находит больше, чем 1 или 2 продукта (диапазон 4), чтобы остановить поиск (сейчас он возвращает и выдает ошибку, если не находит 2-й или 3-й продукт и не может go искать следующее ключевое слово).

Любой совет будет оценен. Спасибо!

1 Ответ

0 голосов
/ 09 марта 2020

Используйте вспомогательный метод для извлечения HTMLCollection, возвращенного методом getElementsByClassName. Затем вы можете проверить, дал ли метод какие-либо результаты.

Как только вы вернете заполненную коллекцию, вам решать, как ее обработать. Вы можете l oop и заполнить отдельные ячейки или объединить результаты, чтобы заполнить одну ячейку. Кроме того, если Count меньше 2, игнорируйте его и т. Д. c.

Private Function TryExtractElementsByClassName(ByVal ie As Object, 
                                               ByVal className As String, 
                                               ByRef objCollection As VBA.Collection) As Boolean

    'if ie is null, return false
    If ie Is Nothing Then Exit Function

    'if elements (HTMLCollection) is null, return false
    Dim elements As Object
    Set elements = ie.Document.getElementsByClassName(className)
    If elements Is Nothing Then Exit Function

    'fill collection
    Dim element As Object, idx As Long
    For idx = 0 To elements.Length
        Set element = elements(idx)
        If Not element Is Nothing Then objCollection.Add element
    Next idx

    'return
    TryExtractElementsByClassName = objCollection.Count > 0

End Function

Для вызова вспомогательного метода:

Sub Test()

    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")

    Dim objColl As New VBA.Collection

    'search single class name
    If TryExtractElementsByClassName(ie, "athenaProductBlock_priceValue", objColl) Then
        'handle results stored in objColl
    End If

    'search multiple class names separated by a space
    If TryExtractElementsByClassName(ie, "athenaProductBlock_priceValue athenaProductBlock_fromValue", objColl) Then
        'handle results stored in objColl
    End If

End Sub
...