SeleniumからJavaScriptを実行する

SeleniumからJavaScriptを実行する場合、executeScriptメソッドを利用します。

JavaScriptに渡す引数は、arguments[0], arguments[1]のように指定します。
JavaScript側でreturnすれば、戻り値を取得することができます。

num1 = 10
num2 = 5
sum = driver.execute_script("return arguments[0] + arguments[1];", num1, num2)
print(sum)

15
int num1 = 10;
int num2 = 5;
//Javaの場合、Numberはlongで受ける
int sum = (int)(long)((JavascriptExecutor)driver).executeScript("return arguments[0] + arguments[1];", num1, num2);
System.out.print(sum);

15
        
int num1 = 10;
int num2 = 5;
int sum = Convert.ToInt32((driver as IJavaScriptExecutor).ExecuteScript("return  arguments[0] + arguments[1];", num1, num2));
Console.WriteLine(sum);

15
        
Dim num1 = 10
Dim num2 = 5
Dim sum = driver.ExecuteScript("return  arguments[0] + arguments[1];", num1, num2)
Debug.Print(sum)

15
        
num1 = 10
num2 = 5
sum = driver.execute_script("return arguments[0] + arguments[1];", num1, num2)
puts sum

15
        
var num1 = 10;
var num2 = 5;
var sum = await driver.executeScript("return arguments[0] + arguments[1];", num1, num2);
console.log(sum);

15
        

引数や戻り値には、配列やWebElementなども指定することもできます。

driver.get("https://selenium-world.net/page/test_link1.html")
elements = driver.execute_script("return document.getElementsByTagName('a');")

for element in elements:
    print(element.get_attribute("id"))

link1
link2
link3
link4
link5
driver.get("https://selenium-world.net/page/test_link1.html");
ArrayList<RemoteWebElement> elements = (ArrayList<RemoteWebElement>)((JavascriptExecutor)driver).executeScript("return document.getElementsByTagName('a');");
for (RemoteWebElement element : elements) { System.out.println(element.getAttribute("id")); }

link1
link2
link3
link4
link5
    
driver.Navigate().GoToUrl("https://selenium-world.net/page//test_link1.html");
ReadOnlyCollection<IWebElement> elements = (ReadOnlyCollection<IWebElement>)(driver as IJavaScriptExecutor).ExecuteScript("return document.getElementsByTagName('a');");

foreach(IWebElement element in elements)
    Console.WriteLine(element.GetAttribute("id"));

link1
link2
link3
link4
link5
driver.Navigate().GoToUrl("https://selenium-world.net/page//test_link1.html")
Dim elements = driver.ExecuteScript("return document.getElementsByTagName('a');")

For Each element As IWebElement In elements
    Debug.Print(element.GetAttribute("id"))
Next

link1
link2
link3
link4
link5
driver.get("https://selenium-world.net/page/test_link1.html")
elements = driver.execute_script("return document.getElementsByTagName('a');")

elements.each{|element|
    puts element.attribute("id")
}

link1
link2
link3
link4
link5
await driver.get("https://selenium-world.net/page//test_link1.html");
var elements = await driver.executeScript("return document.getElementsByTagName('a');");

for(var element of elements){
    console.log(await element.getAttribute("id"));
}

link1
link2
link3
link4
link5