JavascriptExecutor error on trying to scroll down the page - javascript

Below is the snippet and getting error as follows :
The method executeScript(String, Object[]) in the type JavascriptExecutor is not applicable for the arguments (String)
Code Snippet :
public class ScrollPage {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\SeleniumWorkSpace\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
System.out.println(driver);
driver.get("https://en.wikipedia.org/wiki/Main_Page");
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scroll(0,2500)");
}
}
How would I fix this?

Try to use it without casting
driver.executeScript("scroll(0,2500)");

Edit the line of code as :
//import
import org.openqa.selenium.JavascriptExecutor;
//cast driver instance to JavascriptExecutor
JavascriptExecutor js = (JavascriptExecutor)driver;
//invove executeScript method
js.executeScript("scroll(0, 2500)");
Note : Put a space between the coordinates

Try this code:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("window.scrollTo(0,2500);");

Please try the following - I was having the same error with JavascriptExecutor not performing scroll downs properly.
public WebElement pollingScroll(By locator) {
WebDriverWait shortWait = new WebDriverWait(driver, 1);
WebElement element = null;
while(element == null) {
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 555);");
try {
element =
shortWait.until(ExpectedConditions.elementToBeClickable(locator));
} catch(Exception e) {}
}
return element;
}

Related

Why doesn't Date Picker in Selenium (using JavaScript for Spice Jet application) take attribute value?

I am using JavaScript for the Date picker in Selenium. My code runs successfully but the date is not selected in the date picker.
public class SpicJetBooking {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver","C:\\Downloads\\chromedriver.exe");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://www.spicejet.com/");
System.out.println("Site Opened");
Thread.sleep(3000);
driver.findElement(By.xpath("//div[contains(text(),'round trip')]")).click();
// driver.findElement(By.xpath("//div[#data-testid='return-date-dropdown-label-test-id']")).sendKeys("Wed, 23 Mar 2022");
// WebElement element = driver.findElement(By.xpath("//div[contains(text(),'Return Date')]"));
WebElement element = driver.findElement(By.xpath("//div[#data-testid='return-date-dropdown-label-test-id']"));
// element.click();
String datVal = "Wed, 23 Mar 2022";
selectDateByJS(driver, element, datVal);
System.out.println("Complete Execution");
}
public static void selectDateByJS(WebDriver driver,WebElement element, String datVal){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("argument[0].setAttribute('value','"+datVal+"');", element);
// String scriptVal = "arguments[0].setAttribute('value','\"+datVal+\"')";
// String scriptVal = "arguments[0].setAttribute('value','12-Mar-2022')";
// js.executeScript(scriptVal, element);
System.out.println("JS Executed");
}
}
I did refer to Selecting calendar date from JavaScriptExecutor in selenium, but in my opinion, the date picker has got changed and this is not working now
I tried:
$x("(//div[text()='Return Date'])/following-sibling::div/child::div")[0].innerText = 'Wed, 23 Mar 2023'
and it's working fine for me. So you need to use:
(//div[text()='Return Date'])/following-sibling::div/child::div** xpath as a locator and update your **selectDateByJS
method line where you are perform js
js.executeScript("argument[0].innerText="+datVal, element);
Complete Code:
public class SpicJetBooking {
static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver","C:\\Downloads\\chromedriver.exe");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
driver.get("https://www.spicejet.com/");
System.out.println("Site Opened");
Thread.sleep(3000);
driver.findElement(By.xpath("//div[contains(text(),'round trip')]")).click();
WebElement element = driver.findElement(By.xpath("(//div[text()='Return Date'])/following-sibling::div/child::div"));
String datVal = "Wed, 23 Mar 2022";
selectDateByJS(driver, element, datVal);
System.out.println("Complete Execution");
}
public static void selectDateByJS(WebDriver driver,WebElement element, String datVal){
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("argument[0].innerText="+datVal, element);
System.out.println("JS Executed");
}
}

Read data from a website using Nashorn

I want to retrieve data from a website using Nashorn script engine
I have the java code where I can retrieve data from a sample website template.
Now I want to call that java file from java script file.
following is the code:
JAVA CODE(Nsample.java):
package sample;
import java.net.*;
import java.io.*;
public class Nsample
{
public static void main(String[] args)
{
String output = getUrlContents("https://freewebsitetemplates.com/");
System.out.println(output);
}
public static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
try
{
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
JAVASCRIPT code:(sample.js)
var n = Java.type('C.JavaFolder.sample.Nsample');
var result = n.getUrlContents("https://freewebsitetemplates.com/");
print(result);
I'm trying to compile javascript code using command prompt but it is showing CLASSNOTFOUNDEXCEPTION.
The command was jjs sample.js.Im assuming I did some mistake in Java.type() function.
Can anyone solve this?
This line is the problematic line:
var n = Java.type('C.JavaFolder.sample.Nsample');
Java.type accepts fully qualified java type name. Based on your Java code, your package seems to be "sample" and class name is "Nsample". So the fully qualified class name would be "sample.Nsample".
You should compile your Java classes and specify the directory in -classpath option (of jjs tool or your java application if you use javax.script API with nashorn).
Instead of calling Java from JavaScript , I tried to call JavaScript from java and worked well.
I created some functions in JavaScript and invoked those functions from Java code.
Following is the code.Hope this helps.
Test.java:
import javax.script.*;
import java.io.*;
import java.util.*;
public class Test{
public static void main(String[] args) throws Exception{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
engine.eval(new FileReader("test.js"));
Invocable invoke = (Invocable)engine;
Object res = invoke.invokeFunction("httpGet","https://www.javaworld.com");
System.out.println(res);
}
}
test.js:
var httpGet = function(theUrl){
var con = new java.net.URL(theUrl).openConnection();
con.requestMethod = "GET";
return asResponse(con);
}
function asResponse(con){
var d = read(con.inputStream);
return d;
}
function read(inputStream){
var inReader = new java.io.BufferedReader(new
java.io.InputStreamReader(inputStream));
var inputLine;
var response = new java.lang.StringBuffer();
while ((inputLine = inReader.readLine()) != null) {
response.append(inputLine);
}
inReader.close();
return response.toString();
}

wait until page loads completely using selenium 3?

public boolean WaitForPageToLoad(){
final ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
public Boolean apply(final WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
}
};
final WebDriverWait wait = new WebDriverWait(this.driver, this.defaultTimeoutinSeconds);
final boolean IsPageLoad = wait.until(pageLoadCondition);
if (!IsPageLoad) {
log.logInfo("Page doesn't load after " + this.defaultTimeoutinSeconds + " seconds");
}
return IsPageLoad;
}
above code was working in selenium 2.53.1 but when I upgraded to Selenium 3.1.X, above code is not compatible. Plaese anyone convert above code to make it compatible with selenium 3. I am getting below error
The method until(Function) in the type FluentWait is not applicable for the arguments (new ExpectedCondition(){})
This code works for me for Selenium3
driver = (new Driver(Driver.Browser.SAFARI)).getDriver();
driver.navigate().to("http://www.epochconverter.com/");
waitForLoad(driver);
static void waitForLoad(WebDriver driver) {
new WebDriverWait(driver, 50).until((ExpectedCondition<Boolean>) wd ->
((JavascriptExecutor) wd).executeScript("return document.readyState").equals("complete"));
}

how to convert jsp page as pdf format?

I tried to convert jsp page to save as pdf by using itext.i downloaded itex.jars and included those in to my project.after that what i will do to get result as pdf page?
Check this link..
http://www.pd4ml.com/examples.htm
Example :
public static void main(String[] args) {
try {
PdfViewerStarter jt = new PdfViewerStarter();
jt.doConversion("http://pd4ml.com/sample.htm", "D:/pd4ml.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
public void doConversion( String url, String outputPath )
throws InvalidParameterException, MalformedURLException, IOException {
File output = new File(outputPath);
java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
PD4ML pd4ml = new PD4ML();
pd4ml.setHtmlWidth(userSpaceWidth);
pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4));
pd4ml.setPageInsetsMM(new Insets(topValue, leftValue, bottomValue, rightValue));
pd4ml.useTTF("c:/windows/fonts", true);
pd4ml.render(new URL(url), fos);
fos.close();
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(output);
} else {
System.out.println("Awt Desktop is not supported!");
}
System.out.println( outputPath + "\ndone." );
}
The statement jt.doConversion("http://pd4ml.com/sample.htm", "D:/pd4ml.pdf");
instead of "http://pd4ml.com/sample.htm" i have to pass dynamic page url and if page is converted into pdf format so that pdf file should be in same format.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.lowagie.text.DocumentException;
public class GenratePdf {
public static void generatePDF(String inputHtmlPath, String outputPdfPath)
{
try {
String url = new File(inputHtmlPath).toURI().toURL().toString();
System.out.println("URL: " + url);
OutputStream out = new FileOutputStream(outputPdfPath);
//Flying Saucer part
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(out);
out.close();
}
catch (DocumentException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
String inputFile = "D:\\mailPages\\pdfTest.jsp";
String outputFile = "D:/mailPages/testpdf.pdf";
generatePDF(inputFile, outputFile);
System.out.println("Done!");
}
}
We are using pd4ml for downloading a content of JSP in PDF form. You can get the jars here.
Keep this code in your JSP after all the imports
<pd4ml:transform
inline="false"
fileName="application.pdf"
screenWidth="815"
pageFormat="A4"
pageOrientation="portrait"
pageInsets="10,10,10,10,points">
You need to send the html contents to a Java servlet/controller and save the xHTML to PDF.
You'll need to use HtmlPipelineContext and XMLWorker
Have a look here:
Converting HTML files to PDF
and here:
http://itextpdf.com/examples/iia.php?id=56

Execute JavaScript using Selenium WebDriver in C#

How is this achieved? Here it says the java version is:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");
But I can't find the C# code to do this.
The object, method, and property names in the .NET language bindings do not exactly correspond to those in the Java bindings. One of the principles of the project is that each language binding should "feel natural" to those comfortable coding in that language. In C#, the code you'd want for executing JavaScript is as follows
IWebDriver driver; // assume assigned elsewhere
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
string title = (string)js.ExecuteScript("return document.title");
Note that the complete documentation of the WebDriver API for .NET can be found at this link.
I prefer to use an extension method to get the scripts object:
public static IJavaScriptExecutor Scripts(this IWebDriver driver)
{
return (IJavaScriptExecutor)driver;
}
Used as this:
driver.Scripts().ExecuteScript("some script");
the nuget package Selenium.Support already contains an extension method to help with this. Once it is included, one liner to executer script
Driver.ExecuteJavaScript("console.clear()");
or
string result = Driver.ExecuteJavaScript<string>("console.clear()");
How about a slightly simplified version of #Morten Christiansen's nice extension method idea:
public static object Execute(this IWebDriver driver, string script)
{
return ((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = (string)driver.Execute("return document.title");
or maybe the generic version:
public static T Execute<T>(this IWebDriver driver, string script)
{
return (T)((IJavaScriptExecutor)driver).ExecuteScript(script);
}
// usage
var title = driver.Execute<string>("return document.title");
You could also do:
public static IWebElement FindElementByJs(this IWebDriver driver, string jsCommand)
{
return (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(jsCommand);
}
public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
wait.Until(d => d.FindElementByJs(jsCommand));
}
return driver.FindElementByJs(jsCommand);
}
public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand)
{
return FindElementByJsWithWait(driver, jsCommand, s_PageWaitSeconds);
}
public void javascriptclick(String element)
{
WebElement webElement=driver.findElement(By.xpath(element));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",webElement);
System.out.println("javascriptclick"+" "+ element);
}
public static class Webdriver
{
public static void ExecuteJavaScript(this IWebDriver driver, string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(scripts);
}
public static T ExecuteJavaScript<T>(this IWebDriver driver, string scripts)
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
return (T)js.ExecuteScript(scripts);
}
}
In your code you can then do:
IWebDriver driver = new WhateverDriver();
string test = driver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = driver.ExecuteJavaScript<int>(" return 3; ");
Please use the below extension methods added to execute javascript and to take screenshot in Selenium.Support (.dll) of Selenium C#
https://www.nuget.org/packages/Selenium.Support/
IWebDriver driver = new ChromeDriver();
driver.Manage().Window.Maximize();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(20);
driver.Url = "https://phptravels.net/";
driver.ExecuteJavaScript("document.querySelector('#checkin').value='07-12-2022'");
driver.ExecuteJavaScript("document.querySelector('#checkout').value='17-12-2022'");
IWebElement ele1 = driver.FindElement(By.Id("checkin"));
driver.ExecuteJavaScript("arguments[0].value='07-12-2022'",ele1);
string output=driver.ExecuteJavaScript<string>("return
document.querySelector('#checkin').value");
Console.WriteLine(output);
Screenshot sc= driver.TakeScreenshot();
sc.SaveAsFile("C:\\error.png");
The shortest code
ChromeDriver drv = new ChromeDriver();
drv.Navigate().GoToUrl("https://stackoverflow.com/questions/6229769/execute-javascript-using-selenium-webdriver-in-c-sharp");
drv.ExecuteScript("return alert(document.title);");

Categories