我正在使用RSelenium訪問工資頁。如果發生錯誤,偶爾會在頁面上顯示對話框。檢查對話框是否顯示並檢索其內容的正確方法是什麼?檢查RSelenium中的對話框
這個問題其實更一般:當找不到元素時,像findElement
這樣的函數有很多的例外。檢查元素的最佳方法是什麼?每個命令都有單獨的tryCatch
似乎很麻煩。
我正在使用RSelenium訪問工資頁。如果發生錯誤,偶爾會在頁面上顯示對話框。檢查對話框是否顯示並檢索其內容的正確方法是什麼?檢查RSelenium中的對話框
這個問題其實更一般:當找不到元素時,像findElement
這樣的函數有很多的例外。檢查元素的最佳方法是什麼?每個命令都有單獨的tryCatch
似乎很麻煩。
您選擇的例子是框架網頁,讓第一正確幀需要切換到:
appURL <- "http://www.w3schools.com/js/tryit.asp?filename=tryjs_confirm"
library(RSelenium)
RSelenium::startServer()
remDr <- remoteDriver()
remDr$open()
remDr$navigate(appURL)
# This page has frames
remDr$switchToFrame(remDr$findElement("id", "iframeResult"))
webElem <- remDr$findElement("css", "button")
# visually confirm element
webElem$highlightElement()
# click the button to bring up alert
webElem$clickElement()
# Check the Alert text
> remDr$getAlertText()
[[1]]
[1] "Press a button!"
# Accept the alert. Equivalent to pressing the OK button.
remDr$acceptAlert()
根據不同的情況下,你可能還會發現remoteDriver
類有用的sendKeysToAlert
和dismissAlert
方法。
UPDATE:
由於錯誤處理代碼RSelenium
跟蹤異常,併爲它們分配一個狀態代碼的一部分。您可以隨時嘗試撥打電話,然後查看狀態代碼:
> try(remDr$findElement("id", "I DONT EXIST"), TRUE)
> remDr$status
[1] 7
> remDr$statusCodes[which(remDr$statusCodes$Code == remDr$status),]
Code Summary Detail
3 7 NoSuchElement An element could not be located on the page using the given search parameters.
什麼是最好的方式來檢查一個元素是否存在或沒有拋出異常?如果你能想象你訪問的網頁可能有或沒有對話框,可能有或沒有框架,可能或不可能有10個tryCatch子句並不可怕。 – Alex 2014-11-15 17:16:07
我的問題,要清楚,是如何*檢查*如果有東西存在,而不是如何與元素互動 – Alex 2014-11-15 17:17:19
是的,我理解你的問題。我認爲這是一個公平的觀點,並感謝提出這個問題。目前我在selenium服務器拋出一個異常時發出錯誤https://github.com/ropensci/RSelenium/blob/master/R/errorHandler.R#L189。我可以選擇將此錯誤更改爲可以打開和關閉的警告,如果有幫助的話。如果是這樣的話,可以在https://github.com/ropensci/RSelenium/issues上提出問題,我會添加這樣的機制。 – jdharrison 2014-11-15 17:22:46
您能分享您用來訪問網頁的網址和代碼嗎? – lawyeR 2014-11-15 00:09:20
我沒有記住特定的頁面:我正在學習如何使用Selenium,並使用RSelenium介紹小插曲 – Alex 2014-11-15 00:38:43
這裏是一個帶有對話框的頁面示例:http://www.w3schools.com/js /tryit.asp?filename=tryjs_confirm – Alex 2014-11-15 00:39:45