Selenium Cant find element inside Iframe event tho they are visible - java

I have been trying to create code to automatically log in into the website of a game I play called Life is Feudal to gather some information(Everything is legal, I have manually access to the informations I want but it would take years to gather everything).
So here's my code:
public static void main(String[] args) throws InterruptedException {
String Url = "https://lifeisfeudal.com/";
String email = "MYEMAIL";
String password = "MYPASSWORD";
WebDriver driver = setDriver();
// Open Life is feudal home page
driver.get(Url);
/*
* Logging into my account
*/
// Click on sign in button [WORK]
driver.findElement(By.linkText("Sign In")).click();
//Focus the Iframe
driver.switchTo().frame(driver.findElement(By.id("signin")));
/*
* Type in Email
*/
//Try #1 using name (DONT WORK)
driver.findElement(By.name("email")).sendKeys(email);
//Try #2 using xpath (DONT WORK)
driver.findElement(By.xpath("//*[#id=\"react-view\"]/div/div/div/div[2]/form/div[1]/div/input")).sendKeys(email);
/*
* Type in Password
*/
//Try #1 using name (DONT WORK)
driver.findElement(By.name("password")).sendKeys(password);
//Try #2 using xpath (DONT WORK)
driver.findElement(By.xpath("//*[#id=\"react-view\"]/div/div/div/div[2]/form/div[2]/div/input")).sendKeys(password);
/*
* Click the sign in button
*/
//Try (Havent tried it yet)
driver.findElement(By.linkText("Sign in")).click();
//Bring back to default
driver.switchTo().defaultContent();
//Rest of the code
}
And here's the html code inside the Iframe
HTML Iframe
Edit 1: Adding a thread.sleep(3000) after switching frame as suggested by Frank made it work.
I assume it wasnt fully loading the frame and was trying to access something not fully loading that wasnt existing at the time.

Add a Thread.Sleep(3000) after switching to the IFrame to figure out if it's a matter of timing. If so replace the Thread.Sleep(3000) with a more robust way of waiting like Explicit Wait.

Related

Extract Web Elements from an E-Commerce website?

I m trying write a code to access Aliexpress and search for an item, then extract the details, such as, Product name, price, etc.; on page by page to an Excel document. I seek through previous questions posted here to build it. Thanks to that.
Somehow I was able to search the item for first 5 or 6 test runs but then suddenly, Aliexpress asked me to either login or register.
1.) First question, Why any browser won't access the website without registering? Did they recognized my user-agent?
2.) Secondly, Then I was wrote a code to auto log in. Site contains lots of Javascripts, an it is an responsive site. Some html elements appear as we click them. When in the auto log in, my code won't detect the either E-mail or password elements of the page. Is there something preventing it from been detected? How can I solve this?
I here put my sample code:
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
//To input the user's search
Scanner nw1 = new Scanner(System.in);
System.out.println("What do you want to search?");
String a = nw1.nextLine();
//Open the driver
System.setProperty("webdriver.chrome.driver",
"E:\\JetBrains\\webdriver\\chrome\\chromedriver.exe");
WebDriver AE = new ChromeDriver();
//Open the web page and Login in.
AE.get("https://www.aliexpress.com/");
Thread.sleep(2000);
//xpath of account button
AE.findElement(By.xpath("//*[#id="nav-user-account"]/div/div/p[3]/a[2]")).click();
//xpath of Sign in button
AE.findElement(By.xpath("/html/body/div[9]/a")).click();
AE.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//xpath of Email box
AE.findElement(By.xpath("//*[#id=\"fm-login-id\"]")).sendKeys("my-email");
//xpath of password section to type
AE.findElement(By.xpath("//*[#id=\'fm-login-password\']")).sendKeys("my-password");
AE.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// xpath of submit button
AE.findElement(By.xpath("//*[#id="login-form"]/div[5]/button")).click()
Sry kind of my first time here.
Any helpful comments are welcome. Thanks.
It is because following x path in not clicking on account button instead it is clicking on sign in button
AE.findElement(By.xpath("//*[#id="nav-user-account"]/div/div/p[3]/a[2]")).click();
find element through id. Id is available to click on account
"nav-user-account"
while clicking verify that it is unfold through following class
"ng-item nav-pinfo-item nav-user-account user-account-unfold"
if unfold contain than box is open otherwise it is close. If close than click on it.
Try this one first.
Try applying delete cookies ,some sites access data from cache /cookies ,clearing it would solve.Also quit driver at the end of your script and open a new instance i.e driver.manage().deleteAllCookies(); and driver.quit();
xpath in your code needs to be corrected as AE.findElement(By.xpath("//*[#id='nav-user-account']/div/div/p[3]/a[2]")).click();
Use single quotes inside of your xpaths.

Sendkeys without element selenium java

I'm trying to write a simple java based selenium code where I would load a page, give the desired values to username & password.
Once the page loads username is already focused but I can enter values into username or password
Using MAC - Eclipse
I am new to coding sorry so any help would be greatfully received
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://dc1.racbusinessclub.co.uk/login/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Thread.sleep(2000);
driver.findElement(By.tagName("body")).sendKeys("rac-dc");
Thread.sleep(2000);
driver.findElement(By.tagName("body")).sendKeys(Keys.TAB);
Thread.sleep(2000);
Below is basic way of doing it.
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
pause(3);
WebElement button = driver.findElement(By.tagName("button"));
button.sendKeys(Keys.RETURN);
And once logged-in you can assert the url like below
Assert.assertTrue(driver.getCurrentUrl().endsWith("/yourURL"));
You can get username and password id from the browser by Right click on the page and select Inspect.
Even if the field is already focused, you must specify which element you wish to "send the keys" to. So grab the id of the username field, and then use sendKeys, like so:
driver.findElement(By.id("userNameInputBox")).sendKeys("rac-dc");
Also, worth noting that using Thread.sleep in your scripts is bad practice. If there's something you're waiting for, check for the presence of that element, rather than waiting an arbitrary amount of time.
Edit: Actually, seeing your response above I can see you're trying to interact with an alert popup, which you can do with:
driver.switchTo().alert().sendKeys(yourString);
Alternatively, you can skip that entirely and navigate to the page with your credentials in the URL - remember not to hard-code these:
driver.get("http://username:password#http://dc1.racbusinessclub.co.uk/");

Selenium code to open facebook messenger and send a message

I'm just starting to learn a little bit of Selenium scripting (in Java). Currently I'm trying to open a chat box in Facebook and send a message.
I have gotten up to being able to open the chat box through selenium, however I can't figure out how to actually type things into the text box.
Currently here is my code:
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class practice {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com/login/");
driver.manage().window().maximize();
driver.findElement(By.name("email")).sendKeys("myemail#yahoo.com");
driver.findElement(By.name("pass")).sendKeys("myPassword");
driver.findElement(By.id("loginbutton")).click();
driver.findElement(By.name("mercurymessages")).click();
driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
// This has worked randomly. Sometimes the driver will work and open the chat box. Sometimes it will say element not found. I didn't include the full link of the conversation because apparently you don't have to. And it has worked like this in the past.
}
}
My current issue I'd like resolved is: why does this only work sometimes, and how do i find the text box area on the chat box? I did an Inspect Element and the chat box is very odd. It doesn't have anything like an id or a name, so i can't do By.id, or By.name. I can't figure out how to do it with By.cssSelector. This is what the inspect element for the text box looks like:
textarea class="uiTextareaAutogrow _552m" data-ft=".... more stuff here" onkeydown=" more stuff here" style= "more stuff here."
You have to learn Xpath and how to create Relative xpath.The xpath for the textarea
driver.findElement(By.xpath("//textarea[#class='uiTextareaAutogrow _552m']"));
Anyhow I've made few changes that Include instead of clicking on some other message.It will create a new message and send to your friend
driver.findElement(By.name("mercurymessages")).click();
//wait for 20 seconds
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("u_0_5")));
driver.findElement(By.id("u_0_5")).click();//To click on Send a New Message Link
//To enter a name into the to field
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#class='inputtext textInput']")));
WebElement friendName = driver.findElement(By.xpath("//input[#class='inputtext textInput']"));
friendName.sendKeys("Deep");//Change it with your friend name
//wait for the user list to appear
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//li[#class='user selected']")));
friendName.sendKeys(Keys.ENTER);
WebElement messageBox = driver.findElement(By.xpath("//textarea[#class='uiTextareaAutogrow _552m']"));
wait.until(ExpectedConditions.visibilityOf(messageBox));
messageBox.sendKeys("Hi there");
messageBox.sendKeys(Keys.ENTER);
Hi pal hope this gonna help you:
there is a method called By.className so in order to find elements without an id or a name you can use this method, the thing it's that sometimes the class name of the element it's used in other elements, so be aware of the uses in the current page, if you are lucky and the class name is unique then you can use it :)
System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://facebook.com/login");
driver.manage().window().maximize();
Thread.sleep(5000);
driver.findElement(By.name("email")).sendKeys("myemail#yahoo.com");
driver.findElement(By.name("pass")).sendKeys("myPassword");
driver.findElement(By.id("loginbutton")).click();
Thread.sleep(5000);
driver.findElement(By.name("mercurymessages")).click();
Thread.sleep(7000);// here you have to use ExpectedConditions in order to verify that the elemnt it´s "clickable"
driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
Thread.sleep(5000);
WebElement mssgbox = driver.findElement(By.cssSelector("textarea[class*='uiTextareaAutogrow _552m']"));
mssgbox.click();
mssgbox.sendKeys("hi");
hope this help you.
and some times elements in the pages changes so use ExpectedConditions to be sure the element its on the page
How to send message to your friend on Facebook:: Using Selenium WebDriver
// Find Username and Enter
driver.findElement(By.id("email")).sendKeys("Email");
System.out.println("Email");
// Find Password and Enter
driver.findElement(By.id("pass")).sendKeys("Password");
System.out.println("Password");
// Click Login
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//*[#id='u_0_q']")).click();
System.out.println("LogIn Successfull");
Thread.sleep(2000);
// Message
driver.findElement(By.xpath(".//*[#id='u_0_f']/a/div")).click();
driver.findElement(By
.xpath(".//*[#id='u_0_f']/div/div[3]/div/div[1]/div/div/ul/li[2]/a/div/div[2]/div/div[2]/div/div[1]/strong/span"))
.click();
Thread.sleep(2000);
driver.findElement(By.xpath("//*[#class='_1mf _1mj']//following :: div[11]")).click();
Thread.sleep(2000);
WebElement sendmsg = driver
.findElement(By.xpath("//div[#class='_1ia']/descendant::div[#class='_5rpu' and #role='combobox']"));
sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);
IWebElement messageBox = driver.FindElement(By.ClassName("_1mj"));
messageBox.SendKeys(string.Format("{0} Do not try to scam people anymore!!!", iteratia++));
messageBox.SendKeys(Keys.Enter);
Using C#
I can access the message textbox to insert the message with the first line of code. The second line is inserting the message. The third line is sending it.
Result:

Open link in new tab [duplicate]

I have trawled the web and the WebDriver API. I don't see a way to open new tabs using WebDriver/Selenium2.0 .
Can someone please confirm if I am right?
Thanks,
Chris.
P.S: The current alternative I see is to either load different urls in the same window or open new windows.
There is totally a cross-browser way to do this using webdriver, those who say you can not are just too lazy. First, you need to use WebDriver to inject and anchor tag into the page that opens the tab you want. Here's how I do it (note: driver is a WebDriver instance):
/**
* Executes a script on an element
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
* #param element The target of the script, referenced as arguments[0]
*/
public void trigger(String script, WebElement element) {
((JavascriptExecutor)driver).executeScript(script, element);
}
/** Executes a script
* #note Really should only be used when the web driver is sucking at exposing
* functionality natively
* #param script The script to execute
*/
public Object trigger(String script) {
return ((JavascriptExecutor)driver).executeScript(script);
}
/**
* Opens a new tab for the given URL
* #param url The URL to
* #throws JavaScriptException If unable to open tab
*/
public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element; anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open tab", 1);
}
}
Next, you need to tell webdriver to switch its current window handle to the new tab. Here's how I do that:
/**
* Switches to the non-current window
*/
public void switchWindow() throws NoSuchWindowException, NoSuchWindowException {
Set<String> handles = driver.getWindowHandles();
String current = driver.getWindowHandle();
handles.remove(current);
String newTab = handles.iterator().next();
locator.window(newTab);
}
After this is done, you may then interact with elements in the new page context using the same WebDriver instance. Once you are done with that tab, you can always return back to the default window context by using a similar mechanism to the switchWindow function above. I'll leave that as an exercise for you to figure out.
The Selenium WebDriver API does not support managing tabs within the browser at present.
var windowHandles = webDriver.WindowHandles;
var script = string.Format("window.open('{0}', '_blank');", url);
scriptExecutor.ExecuteScript(script);
var newWindowHandles = webDriver.WindowHandles;
var openedWindowHandle = newWindowHandles.Except(windowHandles).Single();
webDriver.SwitchTo().Window(openedWindowHandle);
I had the same issue and found an answer. Give a try.
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
It will open a new tab you can perform your actions in the new tab.
Though there is no API for opening a new tab, you can just create a new instance of WebDriver calling it something slightly different and passing the URL you want in the new tab. Once you have done all you need to do, close that tab and make the new driver NULL so that it does not interfere with the original instance of Webdriver. If you need both tabs open, then ensure you refer to the appropriate instance of WebDriver. Used this for Sitecore CMS automation and it worked.
Thanks for the great idea #Jonathan Azoff !
Here's how I did it in Ruby:
def open_new_window(url)
a = #driver.execute_script("var d=document,a=d.createElement('a');a.target='_blank';a.href=arguments[0];a.innerHTML='.';d.body.appendChild(a);return a", url)
a.click
#driver.switch_to.window(#driver.window_handles.last)
end
There's no way we can create new TAB or handle tabs using web driver / selenium 2.0
You can open a new window instead.
Hey #Paul and who ever is having issue opening a second tab in python. Here is the solution
I'm not sure if this is a bug within the webdriver or because it isn't compatible yet with mutlitab but it is definitely acting wrong with it and I will show how to fix it.
Issue:
well I see more than one issue.
First issue has to do that when you open a 2nd tab you can only see one handle instead of two.
2nd issue and here is where my solution comes in. It seems that although the handle value is still stored in the driver the window has lost sync with it for reason.
Here is the solution by fixing the 2nd issue:
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #Will open a second tab
#solution for the 2nd issue is here
for handle in browser.window_handles:
print "Handle is:" + str(handle) #only one handle number
browser.switch_to_window(handle)
time.sleep(3)
#Switch the frame over. Even if you have switched it before you need to do it again
browser.switch_to_frame("Frame")
"""now this is how you handle closing the tab and working again with the original tab"""
#again switch window over
elem.send_keys(Keys.CONTROL + "w")
for handle in browser.window_handles:
print "HandleAgain is:" + str(handle) #same handle number as before
browser.switch_to_window(handle)
#again switch frame over if you are working with one
browser.switch_to_frame("Frame")
time.sleep(3)
#doing a second round/tab
elem = browser.find_element_by_xpath("/html/body/div[2]/div[4]/div/a") #href link
time.sleep(2)
elem.send_keys(Keys.CONTROL + Keys.RETURN + "2") #open a 2nd tab again
"""Got it? find the handle, switch over the window then switch the frame"""
It is working perfectly for me. I'm open for questions...
Do this
_webDriver.SwitchTo().Window(_webDriver.WindowHandles.Where(x => x != _webDriver.CurrentWindowHandle).First());
or Last() etc.
PS there is no guarantee that the WindowHandles are in the order displayed on your browser, therefore, I would advise you keep some history of current windows before you do the command to that caused a new tab to open. Then you can compare your stored window handles with the current set and switch to the new one in the list, of which, there should only be one.
#Test
public void openTab() {
//Open tab 2 using CTRL + t keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//Open URL In 2nd tab.
driver.get("http://www.qaautomated.com/p/contact.html");
//Call switchToTab() method to switch to 1st tab
switchToTab();
}
public void switchToTab() {
//Switching between tabs using CTRL + tab keys.
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
//Switch to current selected tab's content.
driver.switchTo().defaultContent();
}
we can use keyboard events and automate opening and switching between multiple tabs very easily. This example is refered from HERE
I must say i tried this as well, and while it seemingly works with some bindings (Java, as far as Jonathan says, and ruby too, apparently), with others it doesnt: selenium python bindings report just one handle per window, even if containing multiple tabs
IJavaScriptExecutor is very useful class which can manipulate HTML DOM on run time through JavaScript, below is sample code on how to open a new browser tab in Selenium through IJavaScriptExecutor:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
object linkObj = js.ExecuteScript("var link = document.createElement('a');link.target='_blank';link.href='http://www.gmail.com';link.innerHTML='Click Me';document.getElementById('social').appendChild(link);return link");
/*IWebElement link = (IWebElement)linkObj;
link.Click();*/
browser.Click("//*[#id='social']/a[3]");
Just to give an insight, there are no methods in Selenium which would allow you to open new tab, the above code would dynamically create an anchor element and directs it open an new tab.
You can try this way, since there is action_chain in the new webdriver.
I'm using Python, so please ignore the grammar:
act = ActionChains(driver)
act.key_down(Keys.CONTROL)
act.click(link).perform()
act.key_up(Keys.CONTROL)
For MAC OS
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://google.com")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.COMMAND + 't')
Java Robot can be used to send Ctrl+t (or Cmd+t if MAC OS X) as follows:
int vkControl = IS_OS_MAC ? KeyEvent.VK_META : KeyEvent.VK_CONTROL;
Robot robot = new Robot();
robot.keyPress(vkControl);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(vkControl);
robot.keyRelease(KeyEvent.VK_T);
A complete running example using Chrome as browser can be forked here.
I would prefer opening a new window. Is there really a difference in opening a new window vs opening a new tab from an automated solution perspective ?
you can modify the anchors target property and once clicked the target page would open in a new window.
Then use driver.switchTo() to switch to the new window. Use it to solve your issue
Instead of opening new tab you can open new window using below code.
for(String childTab : driver.getWindowHandles())
{
driver.switchTo().window(childTab);
}

How to insert text into popup window using selenium WebDriver

I am trying to automate a web page using selenium WebDriver. I can move towards the webpages and can able to do all tasks on parent pages. But at one place I am getting a POPUP window which asks username and password. I am unable to identify the username and password text box id's, how can I find the element (TextBox) and send the username and password through selenium webDriver code.
You can try this by using your web URL,
#Test
public void testlinkedin() throws Exception {
driver.get("https://www.linkedin.com/"); //Use your web URL
driver.findElement(By.linkText("Sign Up")).click();
driver.findElement(By.cssSelector("button.fb-btn")).click();
Thread.sleep(3000);
Set <String>handles = driver.getWindowHandles();//To handle multiple windows
firstWinHandle = driver.getWindowHandle();
handles.remove(firstWinHandle);
String winHandle=handles.iterator().next();
if (winHandle!=firstWinHandle){
secondWinHandle=winHandle;
driver.switchTo().window(secondWinHandle); //Switch to popup window
Thread.sleep(2000);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys("Username");
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys("Password");
driver.findElement(By.id("u_0_2")).click();
driver.findElement(By.name("__CONFIRM__")).click();}
Make sure to declare these string variables as,
public String firstWinHandle;
public String secondWinHandle;
You need to switch to the new pop-up window to select its elements. Here is an example to switch to the new window:
String handle = driver.getWindowHandles().toArray()[1]; // 1 stands for the new window and 0 for the parent window
driver.switchTo(handle);
Now you can select your elements present in this window.
*Note: * To get back to original window you again need to switch back to it with 0 as the index.
Maybe the popup window is HTTP basic authenticated site. If so, then you cannot use the window handles as stated in previous answer, but in that case you have to send the username and password directly to URL request:
driver.get("http://username:password#your-test-site.com");
Its working fine for me as I used like this...
String handle = driver.getWindowHandles().toArray()[1].toString();
driver.switchTo().window(handle);

Categories