【问题标题】:RSelenium: Try if findElement succeeds, then click on it, error: "object of type 'S4' is not subsettable"RSelenium:尝试 findElement 是否成功,然后单击它,错误:“'S4' 类型的对象不是子集”
【发布时间】:2021-05-12 11:11:11
【问题描述】:

我正在用RSelenium 抓取https://www.tandfonline.com/loi/sabo20

我想点击每个li,其文本以20152021 结尾。 xpath 运行良好。

可能缺少一年(例如2021),这就是我使用try()-方法的原因。

  URL <- "https://www.tandfonline.com/loi/sabo20"

  # open RSelenium
  rD <- RSelenium::rsDriver(browser = "chrome", chromever = "90.0.4430.24", port = 4546L, verbose = F)

  remDr <- rD[["client"]]
  remDr$navigate(URL)
  Sys.sleep(4)

  for (yyyy in c(2015:2021)) {
    error <- "Error : \t Summary: NoSuchElement\n \t Detail: An element could not be located on the page using the given search parameters.\n \t class: org.openqa.selenium.NoSuchElementException\n\t Further Details: run errorDetails method\n"

    volumes <- try(unlist(
      remDr$findElement(
        using = "xpath",
        paste0(
          "//li[substring(@id, string-length(@id) - string-length('",
          yyyy,
          "') +1) = '",
          yyyy,
          "']/div"
        )
      )
    ))
    
      if(volumes[1] == error)
        break;
    
    volumes$clickElement()
  }

不幸的是,如果findElement() 成功,if(volumes[1] == error) 会导致错误:

volumes[1] 中的错误:“S4”类型的对象不是子集

在我clickElement() 之前,我如何检查remDr$findElement() 是否成功?

【问题讨论】:

    标签: r try-catch rvest rselenium s4


    【解决方案1】:

    解决方案可以是trycatch

    下面是一个例子。

    URL <- "https://www.tandfonline.com/loi/sabo20"
    
    # open RSelenium
    rD <- RSelenium::rsDriver(browser = "chrome", chromever = "90.0.4430.24", port = 4546L, verbose = F)
    
    remDr <- rD[["client"]]
    remDr$navigate(URL)
    Sys.sleep(4)
    
    for (yyyy in c(1983:2021)) {
    tryCatch(expr = {   
      volumes <- unlist(
        remDr$findElement(
          using = "xpath",
          paste0(
            "//li[substring(@id, string-length(@id) - string-length('",
            yyyy,
            "') +1) = '",
            yyyy,
            "']/div"
          )
        )
      )
      volumes$clickElement()
      Sys.sleep(4)
      },
      error =function(e){          
        message("if you want you can break, but it not necessary")
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2022-09-28
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2017-08-16
      • 1970-01-01
      相关资源
      最近更新 更多