我已经在下面的代码行上苦苦挣扎了几个小时,但我似乎仍然没有接近解决方案。我的代码如下:
#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 进行调试时,看起来好像“问题”列表已正确填充了所有“问题”元素; “问题”项已正确填充列表中的第一个“问题”元素;但是下一行代码的许多变体(旨在获取问题元素中的文本)似乎都失败了,并给出以下错误:
Error in evalq({ : attempt to apply non-function
错误可能来自代码的不同部分,但可能性很小,因为注释掉该行似乎会使其他所有内容都正常工作。
对于你们能够提供的任何帮助,我将非常感激。我正在使用 RSelenium 在 R 中进行编程 - 正如您可能知道的那样,我是 R 新手,尽管我在其他环境中使用 Selenium 的经验非常有限。
预先感谢您的想法!
最佳答案
question
没有名为 getElementText
的函数;它是一个 list
对象,而不是 webElement
对象。您需要 [[
而不是 [
- 查看此示例:
library(RSelenium)
rD <- rsDriver(port=4444L, browser = "phantomjs")
remDr <- rD[["client"]]
remDr$navigate(
"http://stackoverflow.com/questions/43833649/get-element-text-using-rselenium")
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()
关于r - 使用 RSelenium 获取元素文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43833649/