I have a problem to click the element that is within an iframe. Before this step, after clicking one button, a new window is opening and then I am switching to a new window and then I am trying to click the element within an iframe, however without any results. Here you can see the code:
#Test
public void test01() throws InterruptedException {
LoginPageMethods loginPage = new LoginPageMethods();
HomePageMethods homePage = new HomePageMethods();
ShoppingCartMethods shoppingCart = new ShoppingCartMethods();
loginPage.loginToWebsite(Recordset.userName, Recordset.webPassword);
String parentWindow = driver.getWindowHandle();
System.out.println("The current window" + parentWindow);
homePage.goToShoppingCartPage();
//Return a set of window handle
ArrayList<String> windows = new ArrayList<>(driver.getWindowHandles());
System.out.println(windows);
driver.switchTo().window(windows.get(1));
System.out.println(windows.get(1));
//loginPage.loginToWebsite(Recordset.userName, Recordset.webPassword);
WebElement iframe = driver.findElement(By.xpath("//iframe[#id='contentAreaFrame']"));
driver.switchTo().frame(iframe);
List<WebElement> iframes = driver.findElements(By.tagName("iframe"));
int iframecount = iframes.size();
System.out.println("Number of iframes: " + iframecount);
shoppingCart.goToSetValuesOptions();
shoppingCart.setCompanyCode();
(I want to click the Set Values Link)
(inspected the element and this is visible - in Chrome)
(ultimately I need to execute that in Internet Explorer and checked in here via the MRI tool and it didn't recognize the xpath, but in CHrome it does).
Here is what I get in the console:
The current windowCDwindow-84EBD3BA474C418428AACFD82588EAF8
[CDwindow-84EBD3BA474C418428AACFD82588EAF8,
CDwindow-06F8C7313F9C0CF38B35BEA929AC2C0B]
CDwindow-06F8C7313F9C0CF38B35BEA929AC2C0B Number of iframes: 3
org.openqa.selenium.NoSuchElementException: Timed out after 30
seconds. Unable to locate the element
I'm trying to click on web element and enter text inside it.
Steps:
Launch "https://www.phptravels.net/"
Click on tours tab.
Perform send keys operation on search field.
1.I tried using click on search box and entering text via send keys but unable to do so, After that I performed click action and send keys using javaScript but this is also not working.
I have written different xpath for the same but no positive results.
//code is as below
public class HandlingDropDown2 {
static WebElement element;
static WebDriver driver;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "Driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.phptravels.net/");
element = driver.findElement(By.xpath("//span[contains(text(),'Tours ')]"));
element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//button[contains(text(),'Got it!')]"));
element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//div[#id='s2id_autogen5']"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
System.out.println("clicked on autogen box");
//element.click();
Thread.sleep(2000);
element = driver.findElement(By.xpath("//div[#class='select2-drop select2-display-none select2-with-searchbox select2-drop-active']"));
JavascriptExecutor executor2 = (JavascriptExecutor)driver;
executor2.executeScript("arguments[0].'value='Test';",element);
//element.sendKeys("test");
}
}
Expected Result: User must be able to enter some text via automation.
Actual Result: Unable to perform click and sendkeys using JavaScript and simple selenium methods.
Remember the functionality of sendKeys
Fir of all, your xPath is div element and you are trying to do sendKeys in div element which is wrong. If you observed there is span element named 'Search by Listing or City Name'. If you click there then your input element gets visible where you can click() and sendKeys("")
Try,
// click on below span element to get input visibled,
element = driver.findElement(By.xpath("//span[text()='Search by Listing or City Name']"));
element.click();
Then your input element is now available where you can click and sendkeys
element = driver.findElement(By.xpath("//div[#id='select2-drop']//input[#class='select2-input'][last()]"));
element.click();
element.sendKeys("test");
Select se = new Select(driver.findElement(By.xpath(".//*[#id='33629']/div/div[1]/div[2]/div[1]/select")));
se.selectByIndex(7);
driver.findElement(By.xpath(".//*[#id='33629']/div/div[1]/div[2]/div[1]/select/option[8]")).click();
Above code doesn't work,please help
Error returned:
Exception in thread "main" org.openqa.selenium.NoSuchWindowException: no such window: target window already closed from unknown error: web view not found
org.openqa.selenium.NoSuchWindowException: no such window
Means the browser is close when you are trying to interact with it. Remove driver.close() from your code and put it only after you have finished all you interactions with the browser.
Edit
If you need to return to parent window after closing child window use driver.switchTo() again
// get parent window ID
String parentHandle = driver.getWindowHandle();
// switch to the new window
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parentHandle))
{
driver.switchTo().window(handle);
}
}
//do something with the new window
// switch back to the old window
driver.close();
driver.switchTo().window(parentHandle);
windowIdbefore = driver.getWindowHandle();
System.out.println(windowIdbefore);
Set<String> windowid = driver.getWindowHandles();
for (String string : windowid) {
System.out.println(string);
driver.switchTo().window(string);
// enter code here
}
WebDriver driver=new FirefoxDriver();
Select s=new Select(driver.findElement(By.xpath("xpathExpression")));
s.selectByVisibleText("text");
s.selectByValue("value");
s.selectByIndex(1);
as i see here the dropdown box is present in div tag. i think with your code dropdown has been located but you are not able to select the value present in dropdown. Then follow below code
WebDriverWait wait = new WebDriverWait(d, 10);
Actions builder = new Actions(d);
WebElement selectvalue = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("your drop down xpath value")));
builder.mouse.mouseMove(((Locatable)selectvalue).coordinates);
selectvalue.click();
WebElement option = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("locator value of dropdown value(your dropdown value)")));
builder.mouse.mouseMove(((Locatable)option).coordinates);
option.click();
System.out.println("dropdown value slected...");
I've just begun using selenium web-driver. I'm trying to use it login and navigate/scrape.
public static void main(String[] args) {
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
WebDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
driver.get("my_Site_I_Reference");
#SuppressWarnings("unused")
WebDriverWait wait = new WebDriverWait(driver, 4000);
WebElement name = driver.findElement(By.id("LoginUsername"));
name.sendKeys("exampleName");
name.submit();
System.out.println("Page title is: " + driver.getTitle());
driver.quit();
}
I'm using the code above to try and enter a username into the username field but I am constantly met with this error:
"org.openqa.selenium.NoSuchElementException: Unable to locate element with ID: LoginUsername"
I'm almost certain the element is called LoginUsername as shown in the picture:
Any help would be very much appreciated, thanks!
It would be still a guess, but I suspect the element is inside an iframe. If this is the case, switch to the iframe before looking for the element:
driver.switchTo().frame("frame_id_or_name");
WebElement name = driver.findElement(By.id("LoginUsername"));
Can you please share HTML code in detail ? Meanwhile, You can also give a try by changing it to below and share what do you see?
WebElement name = driver.findElement(By.xpath(“//*[#id="LoginUsername"]”));
OR
WebElement name = driver.findElement(By.xpath(“//input[#id="LoginUsername"]”));
Turns out that I had Javascript disabled by default I found this out by printing the page source my code loaded
((HtmlUnitDriver) driver).setJavascriptEnabled(true);
Once enabled selenium behaved like I expected
I have the following HTML:
<button name="btnG" class="gbqfb" aria-label="Google Search" id="gbqfb"><span class="gbqfi"></span></button>
My following code for clicking "Google Search" button is working well using Java in WebDriver.
driver.findElement(By.id("gbqfb")).click();
I want to use JavaScript with WebDriver to click the button. How can I do it?
Executing a click via JavaScript has some behaviors of which you should be aware. If for example, the code bound to the onclick event of your element invokes window.alert(), you may find your Selenium code hanging, depending on the implementation of the browser driver. That said, you can use the JavascriptExecutor class to do this. My solution differs from others proposed, however, in that you can still use the WebDriver methods for locating the elements.
// Assume driver is a valid WebDriver instance that
// has been properly instantiated elsewhere.
WebElement element = driver.findElement(By.id("gbqfd"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", element);
You should also note that you might be better off using the click() method of the WebElement interface, but disabling native events before instantiating your driver. This would accomplish the same goal (with the same potential limitations), but not force you to write and maintain your own JavaScript.
Here is the code using JavaScript to click the button in WebDriver:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('gbqfb').click();");
I know this isn't JavaScript, but you can also physically use the mouse-click to click a dynamic Javascript anchor:
public static void mouseClickByLocator( String cssLocator ) {
String locator = cssLocator;
WebElement el = driver.findElement( By.cssSelector( locator ) );
Actions builder = new Actions(driver);
builder.moveToElement( el ).click( el );
builder.perform();
}
Not sure OP answer was really answered.
var driver = new webdriver.Builder().usingServer('serverAddress').withCapabilities({'browserName': 'firefox'}).build();
driver.get('http://www.google.com');
driver.findElement(webdriver.By.id('gbqfb')).click();
You can't use WebDriver to do it in JavaScript, as WebDriver is a Java tool. However, you can execute JavaScript from Java using WebDriver, and you could call some JavaScript code that clicks a particular button.
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('gbqfb').click()");
By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.
WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
This code will perform the click operation on the WebElement "we" after 100 ms:
WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("var elem=arguments[0]; setTimeout(function() {elem.click();}, 100)", we);
Another easiest solution is to use Key.RETUEN
Click here for solution in detail
driver.findElement(By.name("q")).sendKeys("Selenium Tutorial", Key.RETURN);
I think some parts of above codes has changed a little, I'm learning Selenium with JavaScript and I founded 2 options to click
To start we need to find the element we want to click, could be By (id, class, etc.), here is how, https://www.youtube.com/watch?v=BQ-9e13kJ58&list=PLZMWkkQEwOPl0udc9Dap2NbEAkwkdOTV3.
Right down are the 2 ways that I'm talking about:
FIRST Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learning Selenium", Key.RETURN);
- Here we found an empty field by it's Id, and then we write "Learning Selenium" in this field with the sendKeys().
- Key.RETURN: Simulate the person pressing the ENTER key in keyboard.
SECOND Method:
await driver.findElement(By.id("sampletodotext")).sendKeys("Learn Selenium");
await driver.findElement(By.id("addbutton")).click().finally();
- The difference here, is we switched the Key.RETURN of the FIRST method, for the entire second line, in the SECOND method.
Use the code below, which worked for me:
public void sendKeysJavascript() {
String file = getfile();
WebElement browser = driver.findElement(By.xpath("//input[#type='file']"));
JavascriptExecutor js = (JavascriptExecutor) driver;
actionClass.waitforSeconds(5);
js.executeScript("arguments[0].click();", browser);
actionClass.waitforSeconds(1);
browser.sendKeys(file);
}
String getfile() {
return new File("./src/main/resources/TestData/example.pdf").getAbsolutePath();
}
Don't forget to add wait time before the js click action. It is mandatory
Cross browser testing java scripts
public class MultipleBrowser {
public WebDriver driver= null;
String browser="mozilla";
String url="https://www.omnicard.com";
#BeforeMethod
public void LaunchBrowser() {
if(browser.equalsIgnoreCase("mozilla"))
driver= new FirefoxDriver();
else if(browser.equalsIgnoreCase("safari"))
driver= new SafariDriver();
else if(browser.equalsIgnoreCase("chrome"))
//System.setProperty("webdriver.chrome.driver","/Users/mhossain/Desktop/chromedriver");
driver= new ChromeDriver();
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
driver.navigate().to(url);
}
}
but when you want to run firefox you need to chrome path disable, otherwise browser will launch but application may not.(try both way) .