Interacting with Gmail inbox using Selenium webdriver - selenium

I'm working in project where I have to buy a product from some website. I'll get a mail in Gmail I have to click on Received Email (Unread Mail) and interact with the clicked element.
So far I have bought the product and now I'm stuck with the Gmail; I'm not able to open the unread mail and interact with the element when I click 'Unread Mail'.
here is my code
driver.get("https://www.gmail.com");
driver.manage().window().maximize();
JavascriptExecutor exe = (JavascriptExecutor) driver;
Integer numberOfFrames = Integer.parseInt(exe.executeScript("return window.length").toString());
System.out.println("Number of iframes on the page are " + numberOfFrames);
driver.findElement(By.id("Email")).sendKeys("your mail");
driver.findElement(By.xpath(".//*[#id='next']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement ele4=driver.findElement(By.xpath("//*[#id='Passwd']"));
new WebDriverWait(driver, 30).until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//*[#id='Passwd']"))));
ele4.sendKeys("yourpassword");
driver.findElement(By.xpath("//*[#id='signIn']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
List<WebElement> unreademeil = driver.findElements(By.xpath("//*[#id=':3d']"));
String MyMailer = "StrapUI";
for(int i=0;i<unreademeil.size();i++)
{
if(unreademeil.get(i).isDisplayed()==true)
{
if(unreademeil.get(i).getText().equals(MyMailer))
{
System.out.println("Yes we have got mail form " + MyMailer);
break;
}
else
{
System.out.println("No mail form " + MyMailer);
}
}
}
driver.findElement(By.xpath("//*[#id=':3d']")).click();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thread.sleep(10000);
driver.switchTo().frame(0);
Thread.sleep(5000);
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,500)", "");
Thread.sleep(3000);
}
}

Why do you want to interact with the email using Selenium? Unless you're creating automated tests for Google there shouldn't be a reason to do this with Selenium. The reason for this is that every little change Google makes to Gmail has a chance to break your script and requires modification.
Instead I'd recommend using an 'IMAP' library to help you with this. You can login and get the new messages. Using this you can check whatever it is you want to check in your email.
For example: I was creating integration tests for a company I used to work at. When I used a certain feature an email would be send containing a url. To verify this worked correctly I had to get this email and find the url in it. Next I used Selenium to get the url that was in the email and verified if it redirected me where I expected. I collected the email using imaplib for Python. I logged in, collected my INBOX and fetched the unread messages.

Related

Send keys not working , right xpath and id (Selenium)

Tried sendomg keys , right relative xpath or ID used but still not working properly
Tried using absolute xpath , relative xpath also ID. Tried using selassist and chropath still not working. Could there be something preventing it?
public void LoginWebSystem() {
driver = new ChromeDriver();
driver.get("http://localhost:82");
WebElement email = driver.findElement(By.id("login_username"));
email.sendKeys("superadmin");
System.out.println("Username Set");
WebElement password = driver.findElement(By.id("login_password"));
password.sendKeys("nelsoft121586");
System.out.println("Password Set");
WebElement login = driver.findElement(By.id("login_submit"));
login.click();
System.out.println("Login Button Clicked");
String newUrl = driver.getCurrentUrl();
if(newUrl.equalsIgnoreCase("http://localhost:82/controlpanel.php")){
System.out.println("Login Success");
}
else {
System.out.println("Login Failed");
}
driver.findElement(By.partialLinkText("Product")).click();
System.out.println("Successful in proceeding to Product Page");
driver.findElement(By.id("createlink")).click();
System.out.println("Successful in proceeding to Create Product by Detailed");
driver.switchTo().alert().accept();
System.out.println("Successful in clicking alert button");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
#Test (priority=1)
public void ProductDetails() {
WebElement product = driver.findElement(By.xpath(" //*[#id="text-product"]"));
product.sendKeys("superadmin");
}
}
Expected output should input superadmin to product textbox
You have a typo in your XPath expression:
WebElement product = driver.findElement(By.xpath(" //*[#id="text-product"]"));
^ remove this space break
It's better to use By.Id locator strategy where possible as this is the fastest and the most robust way of identifying elements in DOM
Consider using Explicit Wait to ensure that the element is present and can be interacted with as it might be the case the element becomes available after document.readyState becomes complete. Check out How to use Selenium to test web applications using AJAX technology article for more detailed explanation.
new WebDriverWait(driver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("text-product")))
.click();
Make sure that your selector matches an <input> because if the id belongs to other element type like <div> it doesn't make a lot of sense to send keys there.

How can i make selenium wait till the next page is loaded with same URL and have same fields

I have this code show below:
driver.findElement(By.id("submit")).sendKeys(Keys.ENTER);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
driver.findElement(By.id("search-trigger")).sendKeys("Shampoo");
driver.findElement(By.id("search-trigger")).sendKeys(Keys.ENTER);
I want to search for a product and search option is before and after login page but here i want to do it after login page
I have used
driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
but it doesn't work and i cannot use
WebElement “”= driver.findElement(By.id(""));
as the search option is on both pages
and URL remains same after login also
Per my understanding, in short, you want to ensure user has logged in before searching for a product. However u will not be able to use WebElement “”= driver.findElement(By.id(""));
Did you try explicit wait for the presence of username/logout text...etc
WebElement element = wait.until(ExpectedConditions.elementIsVisible(By.id(>someid>)));
Below worked for me, tried searching Samsung after login in flipkart:
public static void f() throws InterruptedException
{
By signin = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[9]/a");
Thread.sleep(2000);
By mobile = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[1]/input");
By password = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[2]/input");
By login = By.xpath("html/body/div[2]/div/div/div/div/div[2]/div/form/div[3]/button");
By myaccount = By.xpath(".//*[#id='container']/div/header/div[1]/div[1]/div/ul/li[8]/a");
By search = By.xpath(".//*[#id='container']/div/header/div[1]/div[2]/div/div/div[2]/form/div/div[1]/div/input");
//geko driver for firefox
System.setProperty("webdriver.gecko.driver", "path of geckodriver.exe");
System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.flipkart.com/");
driver.findElement(signin).click();;
driver.findElement(mobile).sendKeys("xxxxxxxxx");
driver.findElement(password).sendKeys("xxxxxxxx");
driver.findElement(login).click();
WebDriverWait wait = new WebDriverWait (driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(myaccount));
driver.findElement(search).sendKeys("samsung");
}

How to handle modal dialog box in Selenium?

There is a scenario where I get the modal dialog box when I tried to login.
I am not able to handle login scenario because webdriver is not getting access to the modal dialog box. Is there any way to handle this?
See the details in below image:
public class TwitterLogin
{
static WebDriver driver;
static String baseUrl="myURL";
public static void main(String[] args)
{
driver= new FirefoxDriver();
driver.get(baseUrl);
driver.manage().window().maximize();
//******Click on Login Link**********//
WebElement LoginButton= driver.findElement(By.xpath("//button[#class='Button StreamsLogin js-login']"));
LoginButton.click();
WebElement UsernameTextbox= driver.findElement(By.xpath("//input[contains(#name,'email]')]"));
UsernameTextbox.clear();
UsernameTextbox.sendKeys("uName");
WebElement PasswdTextbox=driver.findElement(By.xpath("//input[contains(#type,'password')]"));
PasswdTextbox.clear();
PasswdTextbox.sendKeys("1234");
}
}
After clicking on Login button, I'm not able to enter username & password.
just write the following code after click on login button:
Thread.sleep(3000); //i use here wait implicit wait. Try to use explicit wait here.
driver.findElement(By.cssSelector("a.Icon.Icon--close.Icon--medium.dismiss")).click();
In Python , work with Selenium 4 and later versions:
copy selector path
wait to open new dialog
time.sleep(5)
phone_path='div:nth-child(4) > span > div:nth-child(3) > button'
log_in_phone = driver.find_element(By.CSS_SELECTOR, phone_path)
log_in_phone.click()

selenium span link li not working

I am new to selenium. I am practicing to write a test case on http://www.countdown.tfl.gov.uk. Below are the steps I followed:
a) I opened the browser to selenium Web Driver
b) Found the search text Box and enter H32 and clicked on search button to selenium.
Till this part it works fine.
Now on the page I am actually getting two records on the left side of the page under the search. I am actually trying to click on the first one i.e. "Towards Southall,Townhall" link. Nothing is happening.
Below is my code:
public class CountdownTest {
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver)
}
//open the countdowntfl page
private WebDriver openWebDriver(){
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.get("http://www.countdown.tfl.gov.uk");
return driver;
}
private void searchforBus(WebDriver driver,String search){
WebElement searchBox = driver.findElement(By.xpath("//input[#id='initialSearchField']"));
searchBox.sendKeys(search);
WebElement searchButton = driver.findElement(By.xpath("//button[#id='ext-gen35']"));
searchButton.click();
}
private void selectrouteDirection(WebDriver driver){
WebElement towardssouthallLink= driver.findElement(By.xpath("//span[#id='ext-gen165']']"));
((WebElement) towardssouthallLink).click();
}
}
Please help me.
Thanks.
Since you are getting NoSuchElement Exception now, you may try the following code with the usage of WebDriver explicit wait.
WebDriverWait wait = new WebDriverWait(driver, 15);
WebElement towardssouthallLink = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("(//*[#id='route-search']//li/span)[1]")));
towardssouthallLink.click();
Or WebDriver implicit wait
WebDriver driver = WebDriverFactory.getWebDriver("FireFox");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://www.countdown.tfl.gov.uk");
Tips:
The search results need some time to be retrieved, so please use Explicit wait or Implicit wait.
Don't use locators like span[#id='ext-gen165'], they are ExtJs auto generated.
In this case, css selector can also be used: #route-search li:nth-of-type(1) > span
You aren't calling selectrouteDirection.
You probably want:
#Test
public void tflpageOpen(){
WebDriver driver = openWebDriver();
searchforBus(driver,"H32");
selectrouteDirection(driver);
}
You also don't need to cast here:
((WebElement) towardssouthallLink).click();
It's already a WebElement anyway.
I found that id for those links are dynamically generated. ids are of the form 'ext-genXXX' where XXX is number which is dynamically generated hence varies each time.
Actually, you should try with linkText:
For 'Towards Southall, Town Hall'
driver.findElement(By.linkText("Towards Southall, Town Hall")).click
For 'Towards Hounslow, Bus Station'
driver.findElement(By.linkText("Towards Hounslow, Bus Station")).click
Here is a logic:
Get all elements which have id starts with 'ext-gen' & iterate over it & click on link with matching text. Following is Ruby code(sorry, I don't know Java well):
links = driver.find_elements(:xpath, "//span[starts-with(#id, 'ext-gen')]")
links.each do |link|
if link.text == "Towards Southall, Town Hall"
link.click
break
end
end

Tutorial or tips needed to perform a set of web admin tasks using Selenium(Beginner level query)

I'm looking at a few pointers /a tutorial or maybe even another question to help me with my task. I'm looking to automate a web admin task. What I would like to do is :
Login to an application.
Navigate to a particular menu.
Search for a particular item through a search bar.
If the item is displayed in the search items then click on a set of buttons on the UI and proceed with the task.
If the item is not displayed in the search results then continue searching till the item is displayed , and then perform step 4.
I have been able to perform up to step 3 using the selenium IDE plugin for Firefox. But I'm not quite sure how to proceed and where to incorporate the logic for steps 4 and 5. Do I use a programming language?(If yes, then how?)
You hit the limits of the IDE pretty quickly. The IDE doesn't incorporate logic, but it is good for quick and dirty automation tasks, figuring out locator id's, and helping people learn the basics of selenium. I would suggest checking out learning how to script in Selenium Webdriver. Documentation: http://seleniumhq.org/docs/03_webdriver.html
So for example if you're using Java (this was stolen from the documentation):
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");;
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
//Pseudocode
if(element.isDisplayed()){
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
}
else{
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
}
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}