【问题标题】:Try catch for RSelenium errors尝试捕获 RSelenium 错误
【发布时间】:2018-02-26 17:50:25
【问题描述】:

我使用 RSelenium 来检查一些页面。

我使用 for 循环访问此页面。

但有时我会收到此错误:

Selenium message:stale element reference: element is not attached to the page document
  (Session info: chrome=64.0.3282.167)
  (Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 6.3.9600 x86_64)

Error:   Summary: StaleElementReference
     Detail: An element command failed because the referenced element is no longer attached to the DOM.
     Further Details: run errorDetails method

我的程序停止了。

因为我从未在 RSelenium 中使用过 try catch,我该如何编写以在 for 循环中添加 try catch?

我从一个 python 示例中找到了这个:

for x in range(0, len(df.index)):
       try:
           twitter(df.username[x])
           print x
       except TweepError:
           pass

知道TweepError 并传递错误并进入下一次迭代。

我在 r 中有一个相同的 for 循环:

for (i in 1:nrow(df)) {
  url <- df$page[i]
  testpage(url)
}

怎么可能做出像 python ir r 这样的东西?

我尝试过这样的事情:

for (i in 1:nrow(df)) {
  url <- df$page[i]
  try(testpage(url))
}

但我收到错误:

Error in testpage(url) : could not find function "testpage"

我已经在for之前运行过这个函数,我可以在环境变量中看到它,名字是对的。

【问题讨论】:

  • 请包含您正在运行的导致此错误的代码。
  • @C.Braun 提供它的代码有点大,但是否可以包含一个示例,其中没有输入的函数在 python try: twitter() except TweepError: pass
  • @C.Braun 我已经更新了我的问题。感谢您的帮助。

标签: r rselenium


【解决方案1】:

python 的try 最接近的等价物是tryCatch

for (i in 1:nrow(df)) {
  url <- df$page[i]
  tryCatch({
    testpage(url)
  }, error = function( err ) {
    print(paste( "Error:", err ))
    # You can run more code here
    # ...
  })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-21
    • 2019-06-29
    相关资源
    最近更新 更多