R语言 使用Rselenium向元素发送鼠标事件
在这篇文章中,我们将学习如何使用Rselenium包来实现网络应用的自动化。我们还将学习如何使用RSelenium将鼠标事件发送到网络应用中。
一步一步的实现
第1步: 在Rstudio中创建一个名为Rselenium.R的新文件。
第2步: 使用以下代码将RSelenium包导入Rstudio。
# load library
library(RSelenium)
第3步: 用Chrome网络驱动创建一个新的Rselenium服务器。这将创建一个新的Rselenium服务器,并将启动Chrome网络驱动器。
# start the Selenium server
rdriver <- rsDriver(browser = "chrome", # browser name
port = 3230L, # port number
chromever = "98.0.4758.102", # chrome browser version
)
第4步: 从我们之前创建的Rselenium服务器中创建一个新的客户端对象。
# creating a client object and
# opening the browser
remDr <- rdriver$client
第5步: 使用以下代码在浏览器中打开该URL。
# navigate to the url
remDr$navigate("http://www.google.com/ncr")
第6步: 使用以下代码通过CSS选择搜索元素。
# finding query css from the page
webElem <- remDr$findElement(using = "css", "[name = 'q']")
这里,q代表查询。现在,为了发送搜索关键词,我们正在使用sendKeysToElements方法。
# sending the search keyword
webElem$sendKeysToElement(list("GeeksforgGeeks", key = "enter"))
第7步: 现在,我们将使用以下代码从搜索结果中找到所有的URL链接。之后,我们将把所有的URL链接存储到一个列表中。然后,我们将找到符合我们搜索关键词的URL标题。
# finding all the URL links from the search result
webElems <- remDrfindElements(using = "css selector", "h3")
# storing the list of titles
resHeaders <- unlist(lapply(webElems, function(x) {xgetElementText()}))
# checking if the title matches within the list of URLs
webElem <- webElems[[which(resHeaders == "GeeksforGeeks |\
A computer science portal for geeks")]]
第8步: 现在,我们将简单地发送一个鼠标事件点击来点击URL链接。
# clicking on the URL
webElem$clickElement()
第9步: 关闭Rselenium浏览器和服务器。
# closing the server
remDr$close()
以下是完整的实现方案
# R program to demonstrate mouse event using Rselenium
# load the required packages
library(Rselenium)
# start the Selenium server
rdriver <- rsDriver(browser = "chrome", # browser name
port = 3230L, # port number
chromever = "98.0.4758.102", # chrome browser version
)
# creating a client object and opening the browser
remDr <- rdriverclient
# navigate to the url
remDrnavigate("http://www.google.com/ncr")
# finding query css from the page
webElem <- remDrfindElement(using = "css", "[name = 'q']")
# sending the search keyword
webElemsendKeysToElement(list("GeeksforgGeeks", key = "enter"))
# finding all the URL links from the search result
webElems <- remDrfindElements(using = "css selector", "h3")
# storing the list of titles
resHeaders <- unlist(lapply(webElems, function(x) {xgetElementText()}))
# checking if the title matches within the list of URLs
webElem <- webElems[[which(resHeaders == "GeeksforGeeks | A \
computer science portal for geeks")]]
# clicking on the URL
webElemclickElement()
# closing the server
remDrclose()