I just discovered Selenium and I'm trying to learn how to use it with PhantomJS. The first example I've found was about getting a list of links from booking.com.
I tried running it with PhantomJS without luck. Firefox runs it well. The code in java looks like this:
private void start() {
Capabilities caps = new DesiredCapabilities();
((DesiredCapabilities) caps).setJavascriptEnabled(true);
((DesiredCapabilities) caps).setCapability("takesScreenshot", true);
((DesiredCapabilities) caps).setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "D:\\phantomjs-2.0.0-windows\\bin\\phantomjs.exe");
//WebDriver driver = new PhantomJSDriver(caps);
WebDriver driver = new FirefoxDriver();
driver.get("http://www.booking.com");
driver.findElement(By.id("destination")).sendKeys("Berlin");
//saveSShot(driver, "sel1.png");
long timeOut = 5000;
long end = System.currentTimeMillis() + timeOut;
while (System.currentTimeMillis() < end) {
if (String.valueOf(
((JavascriptExecutor) driver)
.executeScript("return document.readyState"))
.equals("complete")) {
break;
}
}
//saveSShot(driver, "sel2.png");
try {
//writeFile(driver, "output1.txt");
new WebDriverWait(driver, 3).until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("ul.ui-autocomplete li a"))).click();
//writeFile(driver, "output2a.txt");
//saveSShot(driver, "sel3.png");
driver.findElement(By.name("idf")).click();
driver.findElement(By.className("b-searchbox-button")).submit();
List<WebElement> list = driver.findElements(By
.cssSelector("a.hotel_name_link"));
for (WebElement webElement : list) {
System.out.println(webElement.getText());
}
} catch (TimeoutException e) {
System.out.println(e.toString());
//writeFile(driver, "output.txt");
}
}
Note the two declarations of driver. If I use Firefox, the WebDriverWait works. On PhantomJS it gives an error with WebDriverWait (Element not found :262 in error)
I have added all code. You can paste it in a new project, add the class and includes and you'll see how it (not) work. The two commented method saveSShot and writeFile must be written. I used them for debugging purposes. What I see on the second screenshot is that "Berlin" is in fact written, but the ajax dropdown isn't there. With Firefox it appears.
This has nothing to do with ghostDriver: this is a generic WebDriver usage case. You need to define such a scenario yourself, most probably by registering some JS in the page to do the check for you, and use the driver to pick up the result. You should provide a mechanism that waits for this element to be displayed and enabled. Waiting for the page's ready-state. Such simple solution can do the trick:
long timeOut = 5000;
long end = System.currentTimeMillis() + timeOut;
while (System.currentTimeMillis() < end) {
if (String.valueOf(
((JavascriptExecutor) driver)
.executeScript("return document.readyState"))
.equals("complete")) {
break;
}
}
I've used the ghostDriver for rich content (gaming sites) and it worked pretty well with all the AJAX.
I did some research and this is what I find working too:
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
Here is an article that can help you if you decide to proceed with the JS code.
Related
I'm currently using Selenium for one of my academic assignments regarding quality assurance automation. For this, I'm using a website that is not handled by me or anyone I know.
I have noticed that when I run my test cases, sometimes, advertisements appear on the website in the Chrome window that opens up. Since it is not a pop-up, using disable-popup-blocking does not work. Moreover, since the advertisement doesn't always appear, using a code segment to close the advertisement modal doesn't work either.
The following image depicts an example scenario.
Is there a workaround for this issue? Thank you in advance!
#Test
#Order(2)
public void CovertLang() throws InterruptedException {
// Navigating to 123apps.com website
driver.get("https://123apps.com/");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Accessing the language modal
WebElement langButton = driver.findElement(By.id("language-link"));
langButton.click();
// Wait until the modal opens
wait.until(ExpectedConditions
.visibilityOfElementLocated(By.className("modal-title")));
// Selecting German as the language
WebElement deutschButton = driver.findElement(By.xpath("//a[#href='/de/']"));
deutschButton.click();
Thread.sleep(1000);
// Comparing the web URL
String newURL = driver.getCurrentUrl();
assertEquals("https://123apps.com/de/", newURL);
}
The above shows an example of a test I conducted.
You can disable that ad using the below js code:
// Selecting German as the language
WebElement deutschButton = driver.findElement(By.xpath("//a[#href='/de/']"));
deutschButton.click();
Thread.sleep(1000);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("const elements = document.getElementsByClassName('adsbygoogle adsbygoogle-noablate'); while (elements.length > 0) elements[0].remove()");
deutschButton.click();
// Comparing the web URL
String newURL = driver.getCurrentUrl();
assertEquals("https://123apps.com/de/", newURL);
I'm admittedly REALLY new to Selenium WebDriver, but I've hit a snag when running a rudimentary test in IntelliJ. I'm able to run and pass my test if I put breakpoints in the code and run it in Debug mode and step through the steps. However, when I just click run regularly it fails on the 2nd step saying the following: org.openqa.selenium.WebDriverException: Element is not clickable at point (596.5, 1128.63330078125). Other element would receive the click:
I'm stuck on trying to figure out why it would pass and run as expected in Debug, but not when I run regularly. Here's my test:
public class BF_Test {
private WebDriver driver;
#Test
public void checkURL()
{
WebDriver driver = BrowserFactory.getDriver("firefox");
driver.get("http://www.vizio.com");
WebElement homePagePopup = driver.findElement(By.xpath("//div[#id='modal']/div/a"));
homePagePopup.click();
//NEED TO FIGURE OUT WAIT TIMER OF SOME SORT
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("html body.cms-index-index.cms-index div.page-wrapper div.main.col1-layout div.std section#heroslider.kslider.hero-home.section-wrap.section-wrap-primary div.navi-wrap ul.navi.navi-bind.navi-count-3 li.item-0")));
WebElement naviButtonsCarousel = driver.findElement(By.cssSelector("html body.cms-index-index.cms-index div.page-wrapper div.main.col1-layout div.std section#heroslider.kslider.hero-home.section-wrap.section-wrap-primary div.navi-wrap ul.navi.navi-bind.navi-count-3 li.item-0"));
naviButtonsCarousel.click();
WebElement homePageTVPButton = driver.findElement(By.cssSelector("#tvp-marquee-inner > div.container > div.content > a.vz-btn"));
homePageTVPButton.click();
WebElement resultsAreInValidation = driver.findElement(By.cssSelector(".thanks.fade-in"));
System.out.println(resultsAreInValidation.getText());
WebElement robinsonBtn = driver.findElement(By.cssSelector("#robinsonHomeVote > span"));
robinsonBtn.click();
WebElement robinsonPlayerText = driver.findElement(By.cssSelector("#modal-container > div > div > div.player > div.playerInfo > section > h1"));
Assert.assertEquals("Verify that Allen Robinson text is on the page","Allen Robinson",robinsonPlayerText.getText());
WebElement btnClose = driver.findElement(By.cssSelector("button.close"));
btnClose.click();
driver.quit();
}
}
So as you can see, nothing crazy to report in what I'm trying to do. Just open a website, click on a couple links and assert on some text and whatnot.
Any thoughts on what I can do to get this to work for me? I've been messing around with WebDriverWait to see if it was Selenium being too quick...but nothing seems to help.
THANKS!
WebDriverException: Element is not clickable at point means the element you want to click on is not visible. You can solve it by scrolling to the element before the click.
WebElement element = driver.findElement(By.cssSelector("selector"));
Actions actions = new Actions(driver);
actions.moveToElement(element).build().perform();
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(element)).click();
Works for me, with the following instructions in C# using Selenium, 3.0 :
Thread.Sleep(TimeSpan.FromSeconds(15));
and then I can create the webElement and send event click.
create an extension like so:
public static class WebDriverExtensions
{
public static IWebElement FindElementUntil(this IWebDriver driver, By by, int waitSeconds = 15)
{
var wait = new WebDriverWait(driver, System.TimeSpan.FromSeconds(waitSeconds));
wait.Until(driver => driver.FindElement(by));
return driver.FindElement(by);
}
}
i have list of Hyperlinks in one page, when i click the links , they are redirecting to the new tab. how do i find out whether the page is loaded or not. i have used the do while loop for find out the element is enabled or not. but i am getting "no such element" only. could you please help on this.. Below is the piece of code. i have tried with Explicit wait also . but getting the same issue.
WebElement element7 = driver.findElement(By.id("MenuControlBNY_MenuNavBar_MenuControlBNY_MenuNavBar_p11__Tree_item_2_cell"));
if (element7.isEnabled())
{
element7.click();
System.out.println(" Report is selected");
}
boolean element8 = false;
int count = 0 ;
do
{
element8 = driver.findElement(By.id("working")).isEnabled();
System.out.println("Report is loaded");
count = count+1;
if(count == 1000)
{
break;
}
}while(element8 == true);
I use the following, its fairly self explanatory.
private static WebDriverWait wait = new WebDriverWait(driver, 60);
private static JavascriptExecutor js = (JavascriptExecutor) driver;
public static void waitForPageLoaded() {
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
Boolean res = (js.executeScript("return document.readyState").equals("complete"));
System.out.println("[DEBUG] waitForPageLoaded: " + res);
return res;
}
});
}
EDIT: This will return true when the page is in a ready state ie the page is loaded. So you would call the above method prior to searching for your element.
You can set an implicit wait which will wait for the elements when finding them for a 15 seconds
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
or explicitly:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("working")));
From the information you have provided, I am assuming you have clicked the link and the page is opened in a new tab and then you are getting nu such elment exception.
In this case you need to switch to the new tab using window handles and use explict wait for element.here is sample code
String parentWindow= driver().getWindowHandle();
element7.click();
Set<String> myset = driver().getWindowHandles();
myset.remove(parentWindow);
driver().switchTo().window((String)myset.toArray()[0]);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(locator)));
I am getting this error while trying to write to simple code in selenium webdriver to enter a value in google search page and enter.
Following is my code -:
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement element=driver.findElement(By.xpath("//input[#id='gs_htif0']"));
boolean b = element.isEnabled();
if (b){
System.out.println("Enabled");
}
element.sendKeys("Test Automation");
element.submit();
Can anyone please help me out with this? How to enable a disabled element?
You are using the wrong 'input' for entering the text. You should be using the following XPath:
//input[#name='q']
Like
WebElement element=driver.findElement(By.xpath("//input[#name='q']"));
This 'input' element accepts the input text just fine.
You can try to run javascript on page:
((JavascriptExecutor) driver).executeScript("document.getElementById('gs_htif0').disabled = false");
or
((JavascriptExecutor) driver).executeScript("arguments[0].disabled = false", element);
See, if this might help,
WebDriver driver = new FirefoxDriver(profile);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
if(element.isEnabled()) {
System.out.println("Enabled");
element.sendKeys("Test Automation");
element.submit();
}
Try this:
WebDriverWait wait = new WebDriverWait(driver, 40);
driver.get("http://www.google.com");
wait.until(ExpectedConditions.visibilityOfElementLocated(By
.xpath("//input[#id='gs_htif0']")));
driver.findElement(By.xpath("//input[#id='gs_htif0']"))
.sendKeys("Test Automation" + Keys.ENTER);
Or:
public boolean isElementPresent(WebDriver driver, By by)
{
try {
driver.findElement(by);
System.out.print("Enabled");
return true;
} catch (NoSuchElementException ignored) {
return false;
}
}
isElementPresent = isElementPresent(
driver, By.xpath("//input[#id='gs_htif0']"));
if (isElementPresent) {
element.sendKeys("Test Automation");
element.submit();
}
Or change xPath to name selector.
If i am correct then you are using the firebug add-on in the firefox driver to get the path for the searchbox. But the firebug seems to provide a path where the Id for the searchbox is not correct. If you use the inspect element option you can see the difference (in the below image you can spot the difference yourself).
OK folks, I've searched the web for 2 days to solve the modal dialog problem. Great information out there and it all works except for IE. I'm trying to open a file upload dialog and select a new file. I created autoIT scripts and they work just fine with FF and Chrome. When I try with IE the "executeScript" does not return back to my test scripts. In IE the "file upload" dialog is opened. But That is where my scripts stops. If I manually run the autoIT script, it returns back to the test script after the "file upload" dialog closes.
//WebDriver driver = new FirefoxDriver();
// processPage(driver);
WebDriver ieDriver =new InternetExplorerDriver();
processPage(ieDriver);
// WebDriver chromeDriver = new ChromeDriver();
// processPage(chromeDriver);
.
.
. other code
.
.
WebElement element = driver.findElement(By.name(uploadDifferntFile));
if (driver instanceof InternetExplorerDriver) {
((InternetExplorerDriver) driver).executeScript("arguments[0].click();", element);
} else if(driver instanceof FirefoxDriver){
((FirefoxDriver) driver).executeScript("arguments[0].click();", element);
} else if(driver instanceof ChromeDriver){
((ChromeDriver) driver).executeScript("arguments[0].click();", element);
}
.
.
. autoIT
.
.
.
try {
Process proc = Runtime.getRuntime().exec(fileToExecute);
} catch (IOException e) {
System.out.println("Failed to execute autoIT");
e.printStackTrace();
}
Thank you for all your support
It seems to be related to modal dialog invoked during your argument[0].click operation in IE, see https://code.google.com/p/selenium/wiki/InternetExplorerDriver, section "Clicking Elements or Submitting Forms and alert()", I think it describes same issue.
Few options to try would be:
Replace your with JavaScript code with just "element.click()" or
"element.sendKeys(Keys.ENTER)"
Start a new thread before you do
argument[0].click, wait in that thread a bit and then run autoIt
code
Also you can replace your existing code with JavascriptExecutor to write JavaSrcipt only once:
WebElement element = driver.findElement(By.name(uploadDifferntFile));
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
}
I've just stepped in the same problem, because sendKeys wasn't a stable solution for me working with Internet Explorer. So I build a variation with AutoIt.
For Firefox I use the JavaScript and for IE I do a doubleclick on the input field:
// fileInput is the WebElement resulting from the input field with type file
if (browser == "FF") {
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", fileInput);
} else {
Actions action = new Actions(driver);
Action doubleClick = action.doubleClick(fileInput).build();
doubleClick.perform();
}