如何使用VBA Selenium获取HTML元素的data-rating属性值
获取HTML元素data-rating属性的VBA实现
Hey there! I totally get where you're coming from—switching between Java and VBA for web automation can feel like learning a slightly different dialect sometimes.
For your specific case, once you've located the element using FindElementByXPath, you just need to use the .Attribute() method (yes, it's that straightforward!) to pull the value from the data-rating attribute.
Step-by-Step Code Example
Let's tie this directly to your HTML structure:
' 假设bot是你的Selenium WebDriver实例 Dim targetElement As Object ' 定位到带有data-rating属性的目标div,也可以用更精准的XPath缩小范围 Set targetElement = bot.FindElementByXPath("//div[@class='star-rating star-rating--alt star-rating--ch'][@data-rating]") ' 提取data-rating属性的值 Dim ratingValue As String ratingValue = targetElement.Attribute("data-rating") ' 验证结果(可选) Debug.Print "Extracted rating: " & ratingValue ' 会在VBA立即窗口输出8.37
额外实用小贴士
- To avoid runtime errors if the element might not exist, add a quick check:
If Not targetElement Is Nothing Then ratingValue = targetElement.Attribute("data-rating") Else MsgBox "Target element not found!" End If - You can also use a CSS selector for more concise targeting:
Set targetElement = bot.FindElementByCss(".star-rating--ch[data-rating]")
内容的提问来源于stack exchange,提问作者Sputnik
相关产品推荐
相关产品推荐

