NoSuchElementError.使用VBA的XPath找不到元素



我正在尝试从tipranks.com上提取分析师对股票的推荐

我有一个电子表格,上面列出了对某只股票提出买入、持有和卖出建议的分析师人数。我使用Selenium和ChromeDriver打开网站,然后找到值(每个推荐的分析师数量)并复制到电子表格中。

代码会一直工作,直到它尝试复制第一个值。它说它找不到元素。

"找不到XPath元素[XPath方向]">

如果我复制完整的XPath,而代码因错误而暂停,从Chrome窗口打开程序,并再次粘贴并单击继续,那么程序将顺利运行,并且会发现网站上的其他元素,尽管XPath与我之前使用的相同。

问题似乎在于,当我运行程序时,它试图找到第一个XPath元素,而不管我试图找到的是什么元素,一旦我解决了这个问题,它就会找到其余的元素。

Dim obj As New WebDriver
Dim xyz As WebElement
Dim destino As Range
obj.Start "chrome", ""
obj.Get "https://www.tipranks.com/stocks/aapl/forecast"
Application.Wait (Now + TimeValue("0:00:5"))
Dim BUYs As Range
Set BUYs = ActiveCell
BUYs = obj.FindElementByXPath("/html/body/div[1]/div/div/div[2]/article/div[2]/div/main/div[1]/section/div[2]/div[1]/div[2]/div/div[2]/div/ul/li[1]/span[2]/b").Text
ActiveCell.Offset(0, 1).Select
Set HOLDs = ActiveCell
Dim HOLDs As Range
HOLDs = obj.FindElementByXPath("/html/body/div[1]/div/div/div[2]/article/div[2]/div/main/div[1]/section/div[2]/div[1]/div[2]/div/div[2]/div/ul/li[2]/span[2]/b").Text
ActiveCell.Offset(0, 1).Select
Dim SELLs As Range
Set SELLs = ActiveCell
SELLs = obj.FindElementByXPath("/html/body/div[1]/div/div/div[2]/article/div[2]/div/main/div[1]/section/div[2]/div[1]/div[2]/div/div[2]/div/ul/li[3]/span[2]/b").Text

我无法在VBA中进行测试,但以下是来自python的翻译,我使用css选择器来定位所需的元素。我以父节点为目标,这样我就可以通过空间分割来生成描述和值,例如购买19。这应该可以避免使用xpath时遇到的问题。

Dim items As WebElements, item As WebElement, tempArr() As String, arr() As Variant, r As Long
ReDim arr(1 To 3, 1 To 2)
items = obj.FindElementByCss('.client-components-pie-style__legend span + span')
For Each item in items
r = r + 1
tempArr = split(item.text, ' ') 
arr(r, 1) = tempArr(0)
arr(r, 2) = tempArr(1)
Next
Activesheet.Cells(1,1).Resize(UBound(arr,1), UBound(arr,2)) = arr

长得吓人的xpath在第一个div[2]上出错了。如果您想坚持使用xpath,我建议使用相对的、更健壮的路径。在匹配方面,与我的css等价的是:

Dim items As WebElements
Set items = obj.FindElementsByXpath('.//*[@class="client-components-pie-style__legendColor"]/following-sibling::span')

最新更新