I am following a code example in selenium and I keep getting the error "Error: Could not find or load main class Test." I am not sure what is causing this as I downloaded and unzipped selenium and extracted the jar files in Eclipse. I also have the class "Test" under the appropriate file and I am not sure what is causing this problem. Here is the code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example {
public static void main(String[] args) {
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new HtmlUnitDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
}
Update your run configuration in Eclipse. It should point to Example class.
Related
I am trying to accept the GDPR Consent window via Selenium (Java), which is placed in an iframe. I understood from the lecture and forums that I have to first switch to that frame (which I did) and then click on the button. However, nothing happens.
Can anyone please help?Thanks
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GDPRiframe {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "/Users/DDD/WebDrivers/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.guru99.com/test/");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
WebElement frameelement = driver.findElement(By.xpath("//iframe[#id='gdpr-consent-notice']"));
driver.switchTo().frame(frameelement);
driver.findElement(By.xpath("//button[#id='save']")).click();
}
}
Verified the css of the object via console, if there is no issue with that - appears to be ok. Also, I tried to click on a link within the frame, also not working. Seems as if I was not switched to the frame.
Thanks
I am fetching the data from a table using selenium chromedriver. When I am opening the webpage normally using my chrome browser, the table is loading correctly. But during execution with selenium, the webpage is loaded but table is not loading. I also removed the implicit wait and just navigated to the webpage to see if the table is loaded or not but still after 10 mins table is not loading, but it loads pretty fine and instantly in chrome browser.
Here is my code:-
package automation;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class table_handling {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver",".\\lib\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.nseindia.com/market-data/top-gainers-loosers");
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(20));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='topgainer-Table']/tbody/tr/td[1]")));
List<WebElement> obj=driver.findElements(By.xpath("//*[#id='topgainer-Table']/tbody/tr/td[1]"));
WebElement temp;
for(int i=0;i<obj.size();i++)
{
temp=obj.get(i);
System.out.println(temp.getText());
}
}
}
For your reference, I am attaching 2 screenshots, one of the normal page which loads pretty fine on chrome browser and 1 of the chromedriver in which table is is loading phase everytime.
Normal chrome Browser
Selenium chromedriver
there is a similar question for the website in case at the following link --> Website Loading Only once then access denied - Selenium Webdriver
Probably the anti-bot protection has something to do with it.
Use the presenceOfElementLocated instead of visibilityOfElementLocated and try it:
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(20));
wait.until(ExpectedConditions.presenceOfElementLocated((By.xpath("//*[#id='topgainer-Table']"))));
I am trying to take screenshot of the table given in one webpage. and the same element xpath I am providing in the code however Ashot code is capturing screenshot of some other location.
I have also tried other code of taking screenshot,
Screenshot screenshot = new AShot().takeScreenshot(driver,driver.findElement(By.xpath(webElementXpath)));
but it was giving me error which I was able to fix by reading this link: https://github.com/pazone/ashot/issues/93 and then I used below code:
WebElement myWebElement = driver.findElement(By.xpath("//center/table/tbody/*"));
Screenshot fpScreenshot = new AShot()
.coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver,myWebElement);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("/Users/sanatkumar/eclipse-workspace/com.ScreenshotUtility/Screenshots/error.png"));
Please help as this code is giving me the screenshot of some random part of the webpage. I tried to capture other element as well but again I did not get the correct screenshot:
Please note my table is not fully visible on the webpage, manually I have to scroll down to view full table. do I need to write other code to get full screenshot of the table??
also my website is angular based which I am trying to automate using selenium java. the reason why I am doing this is because in protractor I dint find any API like Ashot. if anybody knows about it please let me know.
By adding a shootingStrategy I was able to capture just the form element with the attribute id = "post-form" at the bottom of this page.
From the documentation at https://github.com/pazone/ashot
Different WebDrivers take screenshots differently. Some WebDrivers
provide a screenshot of the entire page while others handle the
viewport only.
...
There are built-in strategies in ShootingStrategies for different use cases.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.io.File;
public class Main
{
public static void main(String args[]) throws Exception
{
System.setProperty("webdriver.gecko.driver", "./geckodriver");
System.setProperty("webdriver.firefox.bin", "/usr/bin/firefox");
WebDriver driver = new FirefoxDriver();
driver.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
Thread.sleep(2000);
WebElement webElement = driver.findElement(By.id("post-form"));
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver,webElement);
ImageIO.write(screenshot.getImage(),"PNG",new File("/home/dan/ElementScreenshot.png"));
Thread.sleep(2000);
driver.quit();
}
}
Outputs:
This functionaity is possible with Protractor also by requiring an NPM module like 'protractor-image-comparison'. If you wanted to capture the related posts on the sidebar for instance you could use the following code.
Note: I haven't tested this package out with large elements that extend past the range of the browser viewport so can't say how they will work on those.
Spec File
describe('simple test', () => {
it('will save image', async () => {
await browser.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
await browser.driver.sleep(10 * 1000);
let related_questions_sidebar = element(by.className('module sidebar-related'));
await browser.executeScript('arguments[0].scrollIntoView();', related_questions_sidebar);
await browser.driver.sleep(3 * 1000);
// saveElement
await browser.protractorImageComparison.saveElement(related_questions_sidebar, 'sidebar-image');
});
});
Conf.js- in your OnPrepare
onPrepare: async () => {
// await jasmine.getEnv().addReporter(new dbReporter());
const protractorImageComparison = require('protractor-image-comparison');
browser.protractorImageComparison = new protractorImageComparison(
{
baselineFolder: './screen-compare/baselines/',
screenshotPath: './screen-compare/screenshots/'
}
);
);
Image Saved
I'm working on an auto login using Selenium. I'm able to open the browser and enter and submit the username just fine, but after entering the username, it will sometimes ask you to enter your secret question answer. for whatever reason, it just refuses to enter the secret question answer. oddly enough, it will also occasionally tell me it's unable to locate the element of the text box, but other times it will run and never give the error. Everything seems to work fine up until the if statement, and then it all falls apart.
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String expectedURL = "https://mblogin.verizonwireless.com/amserver";
driver.get("https://sso.verizonenterprise.com/amserver/sso/login.go");
WebElement userId = driver.findElement(By.name("userId"));
userId.sendKeys("username");
userId.submit();
if(driver.getCurrentUrl().equals(expectedURL)){
WebElement answer = driver.findElement(By.name("answer"));
answer.sendKeys("test");
answer.submit();
}
}
}
The if statement itself should be fine, as I have been able to test it by outputting messages to the console, but it doesn't seem to want to fill in the text box and submit the answer.
I think you should try waiting for URL to change with a custom Expected Condition provided here.
Yesterday I posted this Retrieving Data in Java . I'm curious it is possible to make a java program run while a web browser is open and then have it do stuff on a website. If I have facebook open on a browser, could it type the current time in the status box and then click post? Or let's say I make the program able to take input from the user (perhaps using scanner?) and then based on the input, it could load google, type it into the search bar and then click search.
You can do this by using Selenium:
Selenium automates browsers. That's it. What you do with that power is
entirely up to you. Primarily it is for automating web applications
for testing purposes, but is certainly not limited to just that.
Boring web-based administration tasks can (and should!) also be
automated as well.
This is example from documentation page which searches for the term “Cheese” on Google:
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}