2017-05-07 50 views
0

我一直在努力處理幾個小時的下列代碼,現在我似乎還沒有接近解決方案。我的代碼如下:使用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 

這是可能的錯誤來自的不同部分代碼,但不太可能,因爲註釋該行似乎讓所有其他工作都完美無缺。

我會非常感謝任何幫助你們和gals可能提供的幫助。我使用RSelenium在R中進行編程 - 正如您可以說的那樣,雖然我在其他環境中使用Selenium的經驗非常有限,但我對R很陌生。

在此先感謝您的想法!

+0

歡迎SO。請將鼠標懸停在R標籤上 - 它會要求您提供一個最小可重現的示例。你的例子是不可重現的:執行代碼yield _「Error:object'remDr'not found」_。 – lukeA

+0

道歉,盧克,我試圖提供最短的可能的例子來說明問題,但顯然我忽略了一個可重複的例子。下次嘗試做得更好。 – thunderbuck88

+0

除非你聲明你在挖掘一個無法共享的內部工作資源,否則在wld幫助人們知道他們是否正在幫助某人從事盜竊知識產權的事情之後發佈你要去的URL。 – hrbrmstr

回答

3

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()