按 RSelenium 中的提交按钮

Press submit button in RSelenium

我正在尝试点击此处的“开始”按钮: http://ideal-scope.com/online-holloway-cut-adviser/ 我已经开始使用 RSelenium...

library(RSelenium)
RSelenium::startServer()
pJS <- phantom()
Sys.sleep(5) # give the binary a moment
remDr <- remoteDriver(browserName = 'phantomjs')
remDr$open()

...访问了封闭的 iFrame...

remDr$navigate("http://ideal-scope.com/online-holloway-cut-adviser/")
Sys.sleep(5)
webElems <- remDr$findElements("css", "iframe")
remDr$switchToFrame(webElems[[1]])

...并提取按钮。

 subElem   <- remDr$findElement("xpath", '//input[@type="submit"]')

但是当我尝试其中之一时

subElem$sendKeysToElement(list("\uE007"))
subElem$sendKeysToElement(list(key = "space"))

没有任何反应。 我知道我可以访问该页面,因为我已经成功更改了这些输入框中的值。示例:

depthElem <- remDr$findElement("name","depth_textbox")
depthElem$clearElement()
depthElem$sendKeysToElement(list(diamondsDT[theRow]$DepthPct))

现在我正在检查 http://localhost:4444/wd/hub/static/resource/hub.html 以查看网页。按下尝试后,没有任何变化,但我仍然可以在框中看到更新后的值。

无需使用 RSelenium,您可以直接 POST 使用 iframe 的表单。你只需要设置 referer header 如下:

require(httr)
require(rvest)

q <- list(
  depth_textbox = 60,
  table_textbox = 57,
  crown_listbox = 0,
  crown_textbox = 34,
  pavilion_listbox = 0,
  pavilion_textbox = 40.5,
  cutlet_textbox = 0
)

my_url <- "http://www.pricescope.com/hca.php" # url of the iframe:
doc <- POST(my_url,
          body = q, encode = "form",
          # THIS IS THE CRUTIAL LINE
          add_headers(Referer = "http://ideal-scope.com/online-holloway-cut-adviser/")) %>% 
  read_html

现在 doc 是您提交表单后的 iframe 内容。 如果你想提取 img 并绘制它,你可以这样做:

img_url <- doc %>% html_nodes("img") %>% html_attr("src") %>% .[[2]]
tmp_file <- tempfile()
GET(xml2::url_absolute(img_url, my_url), write_disk(tmp_file))
#install.packages("ReadImages")
library('ReadImages')
plot(1:2, type="n")
rasterImage(readJPEG(tmp_file), 1, 1, 2, 2)

这导致: