R语言 如何在RSelenium中按类搜索
在这篇文章中,我们将学习如何使用Rselenium包来实现网络应用的自动化。
Rselenium 是一个免费的、开源的网络自动化工具。Rselenium类似于流行的Selenium,它与python一起工作,是一个全面的网络自动化工具。它是用Java编写的,可用于自动化任何网络应用。在R编程中,我们有一个Rselenium包,可以用来在网页上进行各种单元测试。Rselenium是一个很好的工具,用于自动化网页浏览器,并以比其他软件包更有效的方式搜刮数据。
我们还将学习如何使用Rselenium包按类名搜索一个元素。更具体地说, findElement(using = “class name”, value = “the class name”) 方法被用来按类名搜索元素。
语法
robj$findElement(using = "class", "class name")
例子
<html>
<head>
<title>RSelenium Demonstration</title>
</head>
<body>
<div class="class1">
<h class="class2">Welcome To GFG</h>
</div>
</body>
</html>
现在,如果我们想通过类名来搜索元素。首先,我们必须导入必要的包。然后初始化驱动程序。然后我们必须使用 findElement (using = “class name”, value = “the class name”)方法来搜索元素。
class_content <- rdriver$findElement(using = “class name”, value = “class2”)
如何使用Rselenium包按类名搜索元素?
让我们实际地实现上述搜索方法。 为此,我们将使用geeksforgeeks官方网站。我们试图使用网页右上方的谷歌翻译图标来翻译整个网页。为了达到这个目的,首先我们将使用类名选择图标,然后点击元素。点击翻译后,它将显示各种语言。我们将选择旁遮普语并将网页翻译成旁遮普语,在成功翻译后,我们将使用关闭方法关闭Rselenium服务器和浏览器。
创建一个名为class_search.R的R程序来演示上述搜索方法。
# R program to demonstrate RSelenium
# search element using the class name
# load the required packages
library(Rselenium)
library(tidyverse)
library(netstat)
# start the Selenium server
rdriver <- rsDriver(browser = "chrome", # browser name
port = 8080L, # port number
chromever = "98.0.4758.102", # chrome browser version
)
# creating a client object and opening the browser
robj <- rdriverclient
# navigate to the url
robjnavigate("https://www.geeksforgeeks.org/")
# search for the translate webpage element
# using the class name
translate_element <- robjfindElement(using = 'class name' ,
value = 'gfg-icon_translate')
# clicking on the translate icon
translate_elementclickElement()
# displaying all the supported language
lang <- robjfindElement(using = 'class name',
value = 'goog-te-combo')
langclickElement()
# selecting the punjabi language from the dropdown list
option <- robjfindElement(using = 'xpath',
value = '//*[@id=":0.targetLanguage"]/select/option[76]')
# clicking on the selected option
optionclickElement()
# closing the browser
robj$close()
输出