【问题标题】:Trying to get element by class name VBA Selenium试图通过类名 VBA Selenium 获取元素
【发布时间】:2021-12-07 17:02:29
【问题描述】:

我正在尝试获取 class="woocommerce-Price-amount 金额和其中的文字 20.00

我尝试了各种方法,例如 findelementbyclass 不支持,因为它是一个化合物。

我目前正在尝试让它与 findelementbycss 一起使用,但我收到了 no such element 错误。

<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>
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

【问题讨论】:

  • 需要去掉空格.FindElementByCss(".woocommerce-Price-amount.amount")
  • 它仍然会说“object var or with block var not set”
  • 您忘记使用SET variableName =driver.FindElementByCss(".woocommerce-Price-amount.amount")
  • 它现在在下一行出错-Sheet1.Cells.Value = variableName.Text 它说“应用程序定义或对象定义错误”
  • 知道了。对于任何未来的新手:Sheet1.Cells(1, 1).Value = variableName.Text。非常感谢您的帮助。

标签: excel vba web-scraping selenium-chromedriver


【解决方案1】:

试试这个:

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

打印:

20.00

如果由于excel版本不同导致上述方法失败,请尝试以下操作:

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

在运行上述脚本之前,请务必在库中添加以下引用:

Microsoft HTML Object Library

【讨论】:

  • 运行上述程序时会出现编译错误并说“未定义用户定义的类型”,我正在尝试从页面获取价格并插入到 excel 中。使用 html.queryselector 时仍然显示未定义。
  • 这是因为我们的excel版本不同。我正在使用 excel 2016。但是,试试这个Html.querySelector(".woocommerce-Price-amount &gt; [class$='currencySymbol']").NextSibling.NextSibling.NodeValue。我不确定它是否会像我假设的那样起作用。
  • 另外,查看编辑@Red。
  • with Html.querySelector(".woocommerce-Price-amount > [class$='currencySymbol']").NextSibling.NextSibling.NodeValue。 “它说没有设置块变量的对象”
  • 使用 Html.querySelector(".woocommerce-Price-amount").innerText 显示“无效使用属性”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
  • 2012-01-22
  • 2017-04-03
  • 1970-01-01
  • 2021-01-13
  • 2019-06-11
相关资源
最近更新 更多