Home > Software design >  Trying to get element by class name VBA Selenium
Trying to get element by class name VBA Selenium

Time:10-24

I am trying to get the snippet-code-html lang-html s-code-block"><div class="summary entry-summary"> <div class="summary-container"><h2 itemprop="name" class="product_title entry-title">2&#8243;x 2&#8243; Alumi-guard fence END post for 4&#8242; tall fence</h2> <p class="price"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">&#36;</span>20.00</bdi></span></p> <div class="avada-availability"> </div> <div class="product-border fusion-separator sep-none"></div> <iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Private driver As Selenium.ChromeDriver
Sub test2()

Dim name As String

name = "test"
Set driver = New Selenium.ChromeDriver

Dim By As New By, variableName As WebElement

driver.Start "chrome"

driver.Get "https://www.kandmfence.net/product/2x-2-alumi-guard-fence-end-post-for-4-tall-fence/"

variableName = driver.FindElementByCss(".woocommerce-Price-amount .amount")

Sheet1.Cells.Value = variableName.Text

End Sub

CodePudding user response:

Try this:

Sub GetPrice()
    Const URL$ = "https://www.kandmfence.net/product/2x-2-alumi-guard-fence-end-post-for-4-tall-fence/"
    Dim Html As HTMLDocument
    
    Set Html = New HTMLDocument

    With CreateObject("MSXML2.XMLHTTP")
        .Open "Get", URL, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
        .send
        Html.body.innerHTML = .responseText
    End With

    MsgBox Html.querySelector(".woocommerce-Price-amount > [class$='currencySymbol']").NextSibling.NodeValue

End Sub

Prints:

20.00

In case the above fails because of different excel versions, try the following:

Html.querySelector(".woocommerce-Price-amount").innerText

Before running the above script, be sure to add the following reference to the library:

Microsoft HTML Object Library
  • Related