使用 RSelenium 获取元素文本

Get element text using RSelenium

我已经为以下几行代码苦苦挣扎了几个小时,但我似乎仍然离解决方案还差得很远。我的代码如下:

#create a list of all the question elements on the page
questions <- remDr$findElements(using = 'xpath', "//div[@class='question-text']")

#get the first question element in the list
question <- questions[1]

#get the text of the question element
question$getElementText()

当我使用 RStudio 进行调试时,'questions' 列表似乎已正确填充了所有 'question' 元素; 'question' 项目使用列表中的第一个 'question' 元素正确填充;但是下一行代码的许多变体,旨在获取问题元素中的文本,似乎都失败了,给出以下错误:

Error in evalq({ : attempt to apply non-function

错误可能来自代码的不同部分,但可能性很小,因为注释掉该行似乎使其他一切正常运行。

如果你们能提供任何帮助,我将不胜感激。我在 R 中使用 RSelenium 进行编程——你可能会说,我是 R 的新手,尽管我在其他环境中使用 Selenium 的经验非常有限。

提前感谢您的想法!

question 没有名为 getElementText 的函数;它是 list 对象而不是 webElement 对象。您需要 [[ 而不是 [ - 查看此示例:

library(RSelenium)
rD <- rsDriver(port=4444L, browser = "phantomjs")
remDr <- rD[["client"]]
remDr$navigate(
  "")
elems <- remDr$findElements(using = 'xpath', "//a")
elem <- elems[1]
class(elem)
# [1] "list"
elem$getElementText()
# Error: attempt to apply non-function

现在

elem <- elems[[1]]
class(elem)
# [1] "webElement"
elem$getElementText()
# [[1]]
# [1] "Stack Overflow"
elem$getElementText()[[1]]
# [1] "Stack Overflow"
remDr$close()
rD[["server"]]$stop()