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);
Related
I have problem to automate this drop down using selenium web driver using Java
This is the link - Go to 5th drop down named as Github users (fetch. js)
I am not able to enter the data into search field.
I am using send keys after perform click but it throws an exception like this " element is not interact able"
Steps I follow
driver.findElement(By.xpath("xapth")).click
drop down opens with no options because it is searchable and options are coming dynamically after entering key word into the search field.
driver.findElement(By.xpath("xapth")).sendkeys("Test");
Sendkeys are not working in this case because of drop down closed when perform send keys action.
<div class="Select-placeholder">Select...</div>
Below is the code which is working.
Please do optimize the code by removing thread.Sleep and putting some meaningful waits as per your requirement.
driver.Navigate().GoToUrl("https://jedwatson.github.io/react-select/");
IWebElement element1 = driver.FindElement(By.XPath("//span[#id='react-select-6--value']"));
IWebElement element2 = driver.FindElement(By.XPath("//span[#id='react-select-6--value']/div[2]/input[1]")) ;
element1.Click();
Thread.Sleep(2000);
element2.SendKeys("Test");
Thread.Sleep(1000);
element2.SendKeys(Keys.Tab);
Please note that element2 gets activated once you click on element1.
Try the following code:
public void typeAndSelect() {
WebElement searchBox = driver.findElement(By.xpath("//div[#class='section'][5]//div[#class='Select-control']"));
searchBox.click();
WebElement inputField = driver.findElement(By.xpath("//div[#class='section'][5]//input[#role='combobox']"));
inputField.clear();
String searchWord = "test";
inputField.sendKeys(searchWord);
WebElement selectDropdown = driver.findElement(By.xpath("//div[#class='Select-menu-outer']//div[#role='option'][text()='" + searchWord +"']"));
// wait for search results.
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(selectDropdown)).click();
}
Correct the following xpath part
"//div[#class='section'][5]"
to your implementation of the dropdown
My code begins by signing me into PayPal, then signing into eBay and navigating to the pay fees page, then checking out with PayPal. The final "Continue" button I can't click/submit. I've tried by xpath, id and class. I even tried sending TAB 7x until the Continue button and then sending Enter but that didn't work.
I have found this discussion but I'm not sure how to make it work for me.
PayPal Sandbox checkout 'continue button' - Unable to locate element: - C# WebDriver
Here's a screenshot of the PayPal code and page I'm trying to do.
//Chrome WebDriver specific
System.setProperty("webdriver.chrome.driver", "C:\\automation\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize(); //maximise webpage
WebDriverWait wait = new WebDriverWait(driver, 20);
//navigate to Paypal
driver.get("https://www.paypal.com/uk/signin");
//wait 2.5s for the page to load
try {
Thread.sleep(2500);
}
catch (Exception e) {
e.printStackTrace();
}
WebElement paypalEmail = driver.findElement(By.id("email"));
paypalEmail.sendKeys("******");
//wait 2.5s for the page to load
try {
Thread.sleep(2500);
}
catch (Exception e) {
e.printStackTrace();
}
WebElement paypalSubmit = driver.findElement(By.id("btnNext"));
paypalSubmit.click();
String URL = ("https://www.paypal.com/uk/signin");
driver.get(URL);
WebElement form2 = driver.findElement(By.cssSelector(".main form"));
WebElement username = form2.findElement(By.id("password"));
username.sendKeys("******");
WebElement paypalSubmit2 = driver.findElement(By.id("btnLogin"));
paypalSubmit2.click();
//navigate to Ebay
driver.get("https://signin.ebay.co.uk/ws/eBayISAPI.dll?SignIn&ru=https%3A%2F%2Fwww.ebay.com%2F");
// Enter user name , password and click on Signin button
WebElement form = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#mainCnt #SignInForm")));
form.findElement(By.cssSelector("input[type=text][placeholder='Email or username']")).sendKeys("******");
form.findElement(By.cssSelector("input[type=password]")).sendKeys("******");
form.findElement(By.id("sgnBt")).click();
driver.get("http://cgi3.ebay.co.uk/ws/eBayISAPI.dll?OneTimePayPalPayment");
//WebElement Pay =
driver.findElement(By.xpath("//input[#value='Pay']")).click();
WebDriverWait wait2 = new WebDriverWait(driver, 15);
wait2.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"confirmButtonTop\"]")));
driver.findElement(By.xpath("//*[contains(#id,'confirmButtonTop')]")).click();
}
}
Based on your given screenshot one of following should work to click on continue button :
Method 1 :
WebElement paypalSubmit = driver.findElement(By.xpath("//input[#data-test-id='continueButton']"));
paypalSubmit.click();
Method 2:
By paypalButton=By.xpath("//input[#data-test-id='continueButton']"));
WebElement element=driver.findElement(paypalButton);
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView(true);",element);
js.executeScript("arguments[0].click();", element);
Try 2nd method if you feel your button require bit scroll to bottom to get clickable.
one more xpaths you can use for button if above don't work :
//input[#value='Continue' and #id='confirmButtonTop']
In my experience, paypal likes to use iFrames. If that's true in your case, that means unless you tell webdriver to switch frame contexts, that paypal form will be unavailable to you regardless of your xpath/css selectors.
You can get a list of all available frames currently loaded with this code:
String[] handles = driver.getWindowHandles()
Your actual page will always be the 0th index in that returned array. If paypal is your only iFrame, then you can target the 1th index. Here's a possible solution to that:
String mainPageHandle = handles[0];
String paypalHandle = handles[1];
driver.switchTo().window(paypalHandle);
// Do paypal interactions
driver.switchTo().window(mainPageHandle);
// Back to the main page
There are definitely more robust ways to handle this, and if your page unfortunately has more than one iFrame, then you may need to do more to verify which handle is which, such as test the presence of an element you know is contained within. In general, the frames will load in the same order every time. As a golden path to this problem, this will get you in and out of that iFrame to perform work.
Sometimes the conventional click() doesn't work. In that case, try using the Javascript Executor Click as below.
Make sure you import this class
org.openqa.selenium.JavascriptExecutor
And use this instead of click();
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(“//input[#data-test-id='continueButton']”)));
Try this and let me know if this works for you.
I have written below code to drag an element and add it in workspace. There is no error in console window however drap drop is not performed on chrome browser.
WebElement dragElement = driver.findElement(By.xpath("//*[#id='sidebar-wrapper']/div/div/nginclude/div[2]/accordion/div/div[1]/div[2]/div/div/div[1]/div[2]"));
Thread.sleep(4000);
System.out.println("Element Selected to Drag");
WebElement dropElement = driver.findElement(By.xpath("//*[#id='workspace']/div/div/div/div[2]/div/div/div/div[2]/span"));
Thread.sleep(4000);
act.clickAndHold(dragElement).moveToElement(dropElement).release().build().perform();
I have tried multiple times but not able to succeed. Please provide your inputs
You can try give the location of the element
act.clickAndHold(dragElement).perform();
act.moveToElement(dropElement, dropElement.getLocation().getX(), dropElement.getLocation().getY()).perform();
act.release(dropElement).perform();
This is another method provided in the Selenium documentation here: http://www.seleniumhq.org/docs/03_webdriver.jsp#drag-and-drop.
WebElement dragElement = driver.findElement(By.xpath("//*[#id='sidebar-wrapper']/div/div/nginclude/div[2]/accordion/div/div[1]/div[2]/div/div/div[1]/div[2]"));
WebElement dropElement = driver.findElement(By.xpath("//*[#id='workspace']/div/div/div/div[2]/div/div/div/div[2]/span"));
(new Actions(driver)).dragAndDrop(dragElement, dropElement).perform();
You can use below code for drag and drop but I suggest you to optimize your xpath. It might be the real problem for you.
WebElement source = driver.findElement(By.xpath("//*[#id='sidebar-wrapper']/div/div/nginclude/div[2]/accordion/div/div[1]/div[2]/div/div/div[1]/div[2]"));
Thread.sleep(4000);
System.out.println("Element Selected to Drag");
WebElement target = driver.findElement(By.xpath("//*[#id='workspace']/div/div/div/div[2]/div/div/div/div[2]/span"));
Thread.sleep(4000);
Actions builder = new Actions(driver);
Action mouseOverHome = builder.dragAndDrop(source, target).build();
mouseOverHome.perform();
I had a similar issue in Firefox and resolved it by adding an extra movement instruction in front of the moveToElement() instruction, like this:
private void dragAndDrop(WebElement element, WebElement target) {
Actions builder = new Actions(driver);
builder.clickAndHold(element);
builder.moveByOffset(20,20); // THIS was the critical part for me
builder.moveToElement(target);
builder.release();
builder.perform();
}
I am trying to use an HtmlUnitDriver to login to marketwatch.com. I don't think the program is ever getting past the login prompt, and I did check that I have the correct email and password...
Thank you so much for trying to help me!
Here's my commented code:
static Logger log = Logger.getLogger("com.gargoylesoftware");
public static void main(String[] args) throws InterruptedException {
log.setLevel(Level.OFF);
// Create a new instance of the html unit driver
WebDriver driver = new HtmlUnitDriver();
// Go to marketwatch
driver.get("http://www.marketwatch.com/game/");
System.out.println(driver.getTitle()); // prints 'Virtual Stock Exchange Games (VSE) - MarketWatch.com'
// Click on 'login'
WebElement login = driver.findElement(By.id("profilelogin"));
login.click();
System.out.println(driver.getTitle()); // prints 'Log In'
// Enter username and password
WebElement email = driver.findElement(By.id("username"));
email.sendKeys(Ref.EMAIL);
WebElement pass = driver.findElement(By.id("password"));
pass.sendKeys(Ref.PASSWORD);
// Click submit button
WebElement submit = driver.findElement(By.id("submitButton"));
submit.click();
System.out.println(driver.getTitle()); // prints 'Log In' (same title as before we tried to log in)
// Try to find
WebElement game = driver.findElement(By.xpath("//*[#id='maincontent']/section[1]/table/tbody/tr[1]/td[1]/a"));
// This gets printed to console:
// Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate a node using //*[#id='maincontent']/section[1]/table/tbody/tr[1]/td[1]/a
// I don't think it's ever getting past the login screen...
// You don't really have to read past this, unless you think I might've messed something else up and you want to fix it.
game.click();
WebElement trade = driver.findElement(By.xpath("//*[#id='vse-nav']/ul/li[2]/a"));
trade.click();
WebElement searchBar = driver.findElement(By.className("instrumentsearch ac_input unused"));
searchBar.sendKeys("GOOG");
searchBar.submit();
System.out.println(driver.getTitle());
driver.quit();
}
Try to enable javascript, the website needs it:
// Create a new instance of the html unit driver
WebDriver driver = new HtmlUnitDriver(true);
You can enable JavaScript by doing this way as well:
driver.setJavascriptEnabled(true);
After your submit.click() you can do a dump of the current DOM of the selenium-attached browser that you can examine to determine what Selenium is actually encountering. Doing so via the following code may allow you to view any applicable error messages...maybe there's an error stating that robots aren't allowed to access the site, for example.
System.out.println(driver.getPageSource());
Page has image with hyperlink and that hyperlink has target="_blank" and every time i press that image loads new firefox and that hyperlink is redirected to that new firefox web
and i lose all control of that webpage.
Is possilble to remove or change that target="_blank" on hyperlink, bcause i want to load webpage in same webdriver
WebDriver driver = new FirefoxDriver();
driver.get("http://www.page.eu/");
WebElement submit;
submit = driver.findElement(By.xpath("//img[#alt='page']"));
submit.click();
that hyperlink have target="_blank"
i need to change that target somehow by using webdriver + javascript maybe or what?
is it possible?
edited
thanks for suggestions, but still is this problem
i tried to make like Grooveek said but no changes
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("labels2.setAttribute('target','_self')",labels2 );
aa.click();
i have an error
org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)
i'm not good at javascrit so i think is problem in that executor
Instead of clicking on the image, you could just directly go to the URL in the link:
WebElement link = (driver.findElement(By.xpath("//img[#alt='page']/parent::*"));
String href = link.getAttribute("href");
driver.get(href);
Try the following:
WebElement labels2 = driver.findElement(By.xpath("//a[#href='http://tahtpage.net']"));
WebElement aa = (WebElement) ((JavascriptExecutor) driver).executeScript("arguments[0].setAttribute('target','_self')",labels2 );
aa.click();
You are getting a null exception because you are using labels2 in your javascript, which doesn't exist in that context. By changing it to arguments[0] Selenium will take the labels2 parameter and reference it in javascript appropriately.
Evaluating javascript in the window will help you to suppress target=blank links
Here's the example from the Webdriver docs
List<WebElement> labels = driver.findElements(By.tagName("label"));
List<WebElement> inputs = (List<WebElement>) ((JavascriptExecutor)driver).executeScript(
"var labels = arguments[0], inputs = []; for (var i=0; i < labels.length; i++){" +
"inputs.push(document.getElementById(labels[i].getAttribute('for'))); } return inputs;", labels);
Adapt it to modify the DOM to throw target="_blank links"
Why don't you wanna use SwitchTo().Window?
I think you should use the SwitchTo().Window as suggested by simeon sinichkin. however, i didn't like his example.Here is simple example.
driver.Navigate().GoToUrl(baseURL);
//Get the Main Window Handle
var baseWindow = driver.CurrentWindowHandle;
// navigate to another window (_blank)
driver.FindElement(By.Id("btn_help")).Click();
Thread.Sleep(2000);
//switch back to Main Window
driver.SwitchTo().Window(baseWindow);
hope that helps
Why don't you use:
target="_self"