r - 使用 RSelenium 获取元素文本

标签 r selenium 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 进行调试时,看起来好像“问题”列表已正确填充了所有“问题”元素; “问题”项已正确填充列表中的第一个“问题”元素;但是下一行代码的许多变体(旨在获取问题元素中的文本)似乎都失败了,并给出以下错误:

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/

相关文章:

r - 确定哪些点位于 R 中不规则形状的数据足迹之外?

r - 选择传单上的标记,从 DT 行单击,反之亦然

c# - 如何在 C# 中使用 Selenium 验证是否显示了警报消息?

docker - TightVNC认证失败,如何获取加密密码?

javascript - 使用 R 在搜索后面抓取 asp javascript 分页表

list - 将列表转换为数据框的最有效方法是什么?

r - 基于多行重复值的子集数据框

selenium - Protractor getText 为非空元素返回空字符串

python - 使用 Selenium Webdriver 和 FireFox 时出错

RSelenium:抓取加载缓慢的动态加载页面