// this is the exception I am getting
Exception in thread "main" java.lang.ClassCastException: class sun.net.www.protocol.mailto.MailToURLConnection cannot be cast to class java.net.HttpURLConnection (sun.net.www.protocol.mailto.MailToURLConnection and java.net.HttpURLConnection are in module java.base of loader 'bootstrap')
// this is what I tried
package brokenLinks;
import java.io.IOException;
import java.net.HttpURLConnection;
//import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class ValidateBrokenLinksTest {
public static void main(String[] args) throws IOException {
//set up the webdriver driver
WebDriverManager.chromedriver().setup();
//launch chrome driver
WebDriver driver = new ChromeDriver();
//maximize the window
driver.manage().window().maximize();
//load the url
driver.get("https://testerscafe.in/");
//implicit wait for page to load
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
//get all the links in the webpage using tagName called "a" and store them inside list collection
List<WebElement> elements = driver.findElements(By.tagName("a"));
//get the total number of links available
int size = elements.size();
System.out.println("Number of links available in the webpage :"+size);
//iterate from each link and get the attribute value of each link
for(WebElement links : elements) {
String link = links.getAttribute("href");
//load all the links to URL class
URL url = new URL(link);
//set up the connection
HttpURLConnection connection = (HttpURLConnection)(url.openConnection());
connection.connect();
//validatation
if(connection.getResponseCode()>=400) {
System.out.println(link+" ==> is a broken link");
}
else {
System.out.println(link+" ==> is a valid link");
}
}
//close the webdriver
driver.quit();
}
}
Some of the links on that page are email addresses (info#testerscafe.in). For email links url.openConnection() helpfully returns a MailToURLConnection instead of an HttpURLConnection.
You can exclude the email links and get just the http links with xpath.
Instead of
List<WebElement> elements = driver.findElements(By.tagName("a"));
use
List<WebElement> elements = driver.findElements(By.xpath("//a[starts-with(#href,'http')]"));
See this post regarding how the starts-with xpath works.
Related
Here is my program below on running it I'm getting an error org.openqa.selenium.ElementNotInteractableException.
In this program, I am trying to test a login page with 4 different sets of data using DataProvider annotation so my script is running
Chrome gets initiated
website gets open
click and enter username and password
And the above three steps happen for each set of data provided.
But still on the completion of the whole thing, I'm getting this error. Please help!
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import basePage.*;
//Login to edureka website
public class myPorfileupdate
{
WebDriver driver1;
#Test (dataProvider ="edulogin")
public void myLogin(String username, String password) throws IOException, InterruptedException
{ AppTest a =new AppTest();
driver1 = a.initializeDriver();
driver1.findElement(By.xpath("//span[#data-button-name='Login']")).click();
driver1.findElement(By.xpath("//input[#type='email']")).clear();
driver1.findElement(By.xpath("//input[#type='email']")).sendKeys(username);
driver1.findElement(By.xpath("//input[#type='password']")).sendKeys(password);
driver1.findElement(By.xpath("//*[#id=\"new_sign_up_optim\"]/div/div/div[2]/div[3]/form/button")).click();
Thread.sleep(1000);
driver1.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
try{
WebElement d= driver1.findElement(By.linkText("Trending Courses"));
System.out.println(d);
}
catch (Exception Ex){
// Get text displayes on login page
System.out.println("Userid/password is incorrect");
}
}
#DataProvider(name="edulogin")
public Object[][] testData() {
Object[][] data = new Object[4][2];
data[0][0] = "ambika97.singh#gmail.com";
data[0][1] = "Omsairam#1234";
//2nd row
data[1][0] = "abc";
data[1][1] = "Omsairam#1234";
//3rd row
data[2][0] = "ambika97.singh#gmail.com";
data[2][1] = "xyz";
//4th row
data[3][0] = "abc";
data[3][1] = "xyz";
return data;
}
}```
**First two lines of my console are**
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation.
My first question here! Pardon if i am missing out anything!
I have written code to pick URL from excel and then click on elements in url by fetching corresponding data from the excel sheet. The script runs fine as expected. But it is still throwing Invalid Argument exception after the final run of loop. There are no errors (atleast to my eyes) and i have verified the url links in excel. They are fine. Script currently behaves the way i want. But still i am getting the exception. The final step of driver.close is not performed. Please check the code and let me know where i went wrong.
First column in excel is url. Following columns has text which is picked up by script and used for linktext command to click on the elements in url.
package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidObjectException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver, 20);
String baseUrl = "https://google.com/";
driver.get(baseUrl);
FileInputStream fis = new FileInputStream("D:\\test_data.xlsx");
#SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
int s=sheet.getLastRowNum()+1;
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
driver.close();
}
}
Currently getting this after script runs execution:
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: invalid argument
You can check for null as given below. so that, even though you have empty data in excel, it will work.
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
if(url!=null && !url.isEmpty())
{
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
if(data0!=null && !data0.isEmpty())
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
}
I tried below two codes. Both didn't select the "Male" option. Could anyone please let me know where I'm doing a mistake.
It's very difficult to post the code in this site. So many conditions
My code:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
Select dropdown = new Select (driver.findElement(By.xpath(".//*[#id='Gender']/div")));
dropdown.selectByIndex(1);
}
}
Even I used sendkeys method. But it didn't work for me
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.sendKeys("Male");
google.click();
}
Please suggest me how to overcome this problem
You can use Select() with <select>, <option> elements only. In this current case you can simply click() on drop-down and then click() to choose required option:
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
WebElement option = (driver.findElement(By.xpath("//div[text()='Male']"));
option.click();
You might also need to wait until option to be clickable:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement option = wait.until(elementToBeClickable(By.xpath("//div[text()='Male']")));
option.click();
Simply use this and let me know if it works for you:
For Female
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
For Male
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":f")).click();
For Other
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":g")).click();
For Rather not say
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":h")).click();
And if you need for sign-up gmail, I tried Once:
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F<mpl=default");
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Name");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Last name");
driver.findElement(By.xpath(".//*[#id='GmailAddress']")).sendKeys("Email id");
driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("Password");
driver.findElement(By.xpath(".//*[#id='PasswdAgain']")).sendKeys("Password Again");
//Input the month
List<WebElement> month_dropdown = driver.findElements(By.xpath(".//*[#id='BirthMonth']/div"));
//iterate the list and get the expected month
Thread.sleep(3000);
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
Thread.sleep(3000);
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
driver.findElement(By.id("BirthMonth")).click();
driver.findElement(By.id(":3")).click();
driver.findElement(By.xpath(".//*[#id='BirthDay']")).sendKeys("14");
driver.findElement(By.xpath(".//*[#id='BirthYear']")).sendKeys("1988");
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
driver.findElement(By.xpath(".//*[#id='RecoveryPhoneNumber']")).sendKeys("4694222863");
driver.findElement(By.xpath(".//*[#id='RecoveryEmailAddress']")).sendKeys("recovery email id");
driver.findElement(By.id("submitbutton")).click();
Thread.sleep(3000L);
I'm trying to automate Sign In functionality in www.sears.com, but could not recognize the Email text field using the below code
package com.bigbasket.framework.lab;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Sears {
public static void main(String[] args) {
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.manage().window().maximize();
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
browser.findElement(By.xpath("//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement formElement = browser.findElement(By.id("loginFormDisplay"));
currentElement = formElement.findElement(By.xpath("//*[#id='email']"));
}catch(Exception e){
System.out.println(e.getMessage());
}
WebDriverWait wait = new WebDriverWait(browser, 30);
wait.until(ExpectedConditions.visibilityOf(currentElement));
currentElement.sendKeys("srinimarva#gmail.com");
browser.quit();
}
}
Could you please help me in resolving this? Apologize I'm an amateur in Selenium WebDriver for asking a silly question.
your email field is in iframe so to access it you need to switch to frame first, following is the working code for your issue :
WebDriver browser = new FirefoxDriver();
browser.get("http://www.sears.com/en_us.html");
browser.findElement(By.xpath("//*[#id='gnf_01_tree_item_5']/span/a")).click();
WebElement currentElement = browser.findElement(By.xpath("//*[#id='myProfiles']/div"));
Actions actions = new Actions(browser);
actions.moveToElement(currentElement).build().perform();
WebDriverWait wait = new WebDriverWait(browser, 10);
wait.until(ExpectedConditions.visibilityOf(browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a"))));
browser.findElement(By.xpath(".//*[#id='subnavDD_myProfile']/ul/li[1]/p/a")).click();
try{
WebElement frameElement = browser.findElement(By.xpath(".//iframe[contains(#name, 'easyXDM_default')]"));
browser.switchTo().frame(frameElement);
}
catch(Exception e){
System.out.println(e.getMessage());
}
browser.findElement(By.name("email")).sendKeys("srinimarva#gmail.com");
browser.quit();
I have written a code using Selenium webdriver and Java to open the URL listed in one particular div on the webpage.
The code opens the first URL goes back to the webpage and the throws the error "Element not found in the cache" - perhaps the page has changed since it was looked up.
Please find the code for reference.
import java.util.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenLinks {
public static void OpenLinkAs(String username, String password) throws Exception
{
WebDriver driver;
driver = new FirefoxDriver();
driver.get("http://stg.n**w.le****ine.com/");
driver.findElement(By.name("username")).sendKeys(username);
driver.findElement(By.name("password")).sendKeys(password);
driver.findElement(By.xpath("/html/body/div/div/div[2]/div/form/p[3]/input")).submit();
String content = driver.getPageSource();
if (content.contains("Create new Project"))
{
List<WebElement> elementsList = driver.findElements(By.xpath("//div[#class='recent-project block-link']"));
int RowCount = elementsList.size();
System.out.println(RowCount);
System.out.println(elementsList);
for (int i = 0; i < RowCount; i++)
{
//String oldTab = driver.getWindowHandle();
WebElement url = elementsList.get(i);
//String text= url.getText();
System.out.println(url);
// System.out.println(text);
url.click();
Thread.sleep(5*1000);
driver.navigate().back();
//driver.switchTo().window(oldTab);
}
}
}
public static void main(String[] args) throws Exception
{
OpenLinkAs("username", "password");
}
}
If the element is not found on the page its likely to have been dropped in the DOM. Declare t again and attempt to click it.
What is being returned in the stacktrace, i.e. at what point in the code is the error thrown at?