Selenium Twitter java
I am trying to connect to my Twitter account using Selenium Webdriver
WebDriver driver = new FirefoxDriver();
driver.get("https://www.twitter.com/login/");
WebElement formElement = driver.findElement(By.cssSelector("form.signin"));
List<WebElement> allFormChildElements = formElement.findElements(By.cssSelector("input"));
for(WebElement item : allFormChildElements )
{
System.out.println("<"+item.getTagName()+"> "+ item.getAttribute("name") );
switch(item.getAttribute("name")) {
case "session[username_or_email]":
item.sendKeys(username);
break;
case "session[password]":
item.sendKeys(password);
break;
}
}
But I am getting this error log:
<input> session[username_or_email]
Exception in thread "main" org.openqa.selenium.ElementNotVisibleException: Element is not currently visible and so may not be interacted with
Command duration or timeout: 38 millisecon
DS
I don't understand because it prints the name of the input, why not visible? Any ideas?
thank
source to share
Found that when validating the DOM on the twitter login page, there are two forms having nearly the same properties, and three username and password fields were found. This is why you get ElementNotVisibleException
[See picture]
So for this you need to go with relative xpath or css selections, or implement logic for that. I am proving two ways to handle this situation.
And I don't know why you iterate over all input fields and then find the element by checking its attributes. You can just calldriver.findElements(By.name())
Relative Xpath
How i found the input inside @class
signin-wrapper
is visible i went to this xpath
driver.get("https://twitter.com/login/");
driver.findElement(By.xpath("//div[@class='signin-wrapper']//input[@name='session[username_or_email]']")).sendKeys("viaxpath");
driver.findElement(By.xpath("//div[@class='signin-wrapper']//input[@name='session[password]']")).sendKeys("viaxpath");
Get the visible item
As the name suggests, it will find all elements and return only the element that is visible.
driver.get("https://twitter.com/login/");
getVisibleElement(driver, "session[username_or_email]").sendKeys("viavisibleName");
getVisibleElement(driver, "session[password]").sendKeys("viavisibleName");
public static WebElement getVisibleElement(WebDriver driver, String name) {
List<WebElement> elements = driver.findElements(By.name(name));
for (WebElement element : elements) {
if (element.isDisplayed()) {
return element;
}
}
return null;
}
source to share