按ID搜索 R中的RSelenium
在这篇文章中,我们讨论了如何使用Rselenium包来实现网络应用的自动化。我们还将学习如何使用RSelenium通过id来搜索一个元素。更具体地说, findElement(using = “id”, value = “the id value”) 方法被用来按id搜索一个元素。
语法
object$findElement(using= "id", "value")
例子
<html>
<head>
<title> Rselenium Demo </title>
</head>
<body>
<input type="text" id="txt1" value="Hello">
<input type="text" id="txt2" value="World">
</body>
</html>
输出
现在,如果我们想通过id来搜索元素,我们可以在R中使用以下代码。
id_content <- robj$findElement(using = “id”, value = “txt1”)
这里,我们使用 robj$findElement() 方法,通过id搜索元素。 robj$findElement() 方法需要两个参数。第一个参数是using参数,第二个参数是value参数。using参数用于指定要搜索的元素的类型。值参数用于指定要搜索的元素的值。
逐步实现
第1步: 在Rstudio中创建一个名为Rselenium.R的新文件。
第2步: 使用以下代码将RSelenium包导入Rstudio。
# loading the Rselenium package
library(RSelenium)
第3步: 用Chrome网络驱动创建一个新的Rselenium服务器。
driver <- rsDriver(browser = "chrome", # chrome browser
port = 4444, # default port
chromever = "latest", # latest version of chrome)
这将创建一个新的Rselenium服务器并启动Chrome网络驱动器。
第4步: 从我们之前创建的Rselenium服务器创建一个新的客户端对象。
obj <- rsClient$client
第5步: 使用以下代码在浏览器中打开该URL。
obj$navigate("http://www.geeksforgeeks.org/")
第6步: 使用下面的代码通过id找到元素。我们将在Rselenium中使用元素ID来选择 scroolTotop 按钮。
# 使用元素id选择滚动顶端按钮
id_content <- obj$findElements(using = "id", "scrollTopBtn") [[1]]
第7步: 使用以下代码点击按钮。
# clicking on the scroll to top button
id_content$clickElement()
第8步: 关闭Rselenium浏览器和服务器。
# closing the browser
obj$close()
下面是完整的实现
代码
# R program to demonstrate RSelenium to
# search element using the id
# load the required packages
library(Rselenium)
# start the Selenium server
rdriver <- rsDriver(browser = "chrome",
port = 5050L,
chromever = "98.0.4758.102",
)
# creating a client object and opening
# the browser
obj <- rdriverclient
# navigate to the url
objnavigate("https://www.geeksforgeeks.org/")
# selecting scroll top button using the element id
id_content <- objfindElements(using = "id","scrollTopBtn")[[1]]
# clicking on the scroll to top button
id_contentclickElement()
# closing the browser
obj$close()