Mouseover Selenium with Java - java

I have the following problem: I am using the selenium webdriver with Java and want to extract all links of a webpage. Some links are generated on demand. That means with a mouseover on the menulinks there will be generated more links. When I load the page these links are not there.
I tried to first extract the menu-navigation-links, do a mouseover and then ask the driver for the "new" links. But it seems that there a no "new" links.
WebElement mainNavi = element.findElement(By.className("navigation"));
Actions actions = new Actions(driver);
List<WebElement> menuHoverLinks = new ArrayList<WebElement>();
menuHoverLinks.addAll(mainNavi.findElements(By.cssSelector("a")));
for (WebElement menuHoverLink : menuHoverLinks) {
Actions hoverOverRegistrar = actions.moveToElement(menuHoverLink);
hoverOverRegistrar.perform();
}
First: Is my idea right? Is it possible to do so? If yes, what am I doing wrong?
Thanks in advance!

If the links are generated dynamically then they may not exist initially. You should use Implicit Waits after you click on the menu to allow the webpage to load up the new content before trying to query them.
Instead of using Actions, consider using WebElement, which supports clicking.
For example, You might say something like
// do an implicit wait until the menu is fully loaded
List<WebElement> elmts = driver.findElements(By.cssSelector("a"));
for (WebElement elmt : elmts) {
elmt.click();
}

private static String[] links = null;
private static int linksCount = 0;
public static void main(String[] args){
driver.get("basic url");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
List<WebElement> all_link_webpage=driver.findElements(By.tagName("a"));
linksCount = all_link_webpage.size();
System.out.println(linksCount);
links= new String[linksCount];
for(int i=0;i<linksCount;i++)
{
links[i] = all_link_webpage.get(i).getAttribute("href");
System.out.println(all_link_webpage.get(i).getAttribute("href"));
}
}
This will help you to make a count of all links in the webpage and print the links in the console. i hope it can helpful. Moreover am not sure about mouse hover links.. :) thankq.

Related

How to store value in dropdown using string array? Call in selenium web driver

I am creating script but did not get perfect call. please help me how to create script dropdown value store in array. I an unable to call in selenium web drive.
Dropdown menu scrrenshot: http://prntscr.com/100j0km
Dropdown menu list: http://prntscr.com/100j1og
Thanks
WebElement facultyId = driver.findElement(By.id("faculty_id"));
facultyId.click(); // to make the options to appear
Thread.sleep(500); // if not using implicit wait
List<String> values = new ArrayList<String>();
List<String> texts = new ArrayList<String>();
List<WebElement> options = facultyId.findElements(By.tagName("option"));
for (WebElement option: options) {
values.add(option.getAttribute("value"));
texts.add(option.getText());
}
String[] collectedValues = (String[]) values.toArray();
String[] collectedTexts = (String[]) texts.toArray();
Check Below Answer I have used this script
// options to appear
driver.findElement(By.xpath("//*[#id=\"s2id_autogen3\"]")).click(); // options to appear
Thread.sleep(6000);
driver.findElement(By.xpath("//*[#id=\"s2id_autogen3\"]")).sendKeys("Office Department"); //pass the sendkeys
Thread.sleep(6000);
//Use the Using explicit wait
WebDriverWait Faculties = new WebDriverWait(driver, 120);
WebElement Departments =Faculties.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("*//Put the xpath for finding keyword"))); //Put the xpath for finding keyword
Departments.click(); //Click on finding keyword

Locating WebElement using different locators(NoSuchElementException)

I am having problem with locating WebElement using different locators. In the below html tag I tried locating the "write a review" WebElement with different locators like linkText,xpath,classname but still getting NoSuchElementException
-->url https://www.tripadvisor.in/-->search for Club Mahindra-->click on Club Mahindra-->click on write a review.
<a href="/UserReview-g641714-d1156207-Club_Mahindra_Madikeri_Coorg-
Madikeri_Kodagu_Coorg_Karnataka.html" target="_blank" class="ui_button
primary">Write a review</a>
Locators used
By.xpath("//*[#id="component_12"]/div/div[2]/div/div[2]/div/div[1]/a")
By.xpath("//a[#href='/UserReview-g641714-d1156207-
Club_Mahindra_Madikeri_Coorg-Madikeri_Kodagu_Coorg_Karnataka.html']")
By.className("ui_button primary")
By.linkText("Write a review")
I am really confused. What am I doing wrong?
I have tired to analyse and implement the same. Below are my findings:
-> Application waiting time is more as there are lots of dynamic loads applicable for the page.
-> Proper waits needs to be implemented
-> Check whether all the pages are getting opened in the same tab or clicking on each link is redirecting to new tabs, if so then we have to switch to that particular window.
-> Below code works like a pro for me.
driver.get("https://www.tripadvisor.in/");
WebDriverWait wait = new WebDriverWait(driver, 120);
WebElement ele1 =
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Where to?']")));
ele1.click();
WebElement ele2= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#placeholder='Where to?']")));
ele2.sendKeys("club mahindra, india");
WebElement ele3= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Search for ')]")));
ele3.click();
WebElement ele4= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Club Mahindra Madikeri, Coorg')]")));
ele4.click(); //this click leads to a new tab
Set<String> winHandles = driver.getWindowHandles();
for(String str : winHandles) {
driver.switchTo().window(str);
}
System.out.println(driver.getTitle());
WebElement ele;
int i=1;
while(true) {
try {
ele = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Write a review']")));
break;
}catch(Exception e) {
System.out.print(i++);
}
}
System.out.println();
Actions action = new Actions(driver);
action.moveToElement(ele);
ele.click();
System.out.println("Clicked on the 'Write a review button'");
you can try
//a[contains(text(),'Write a review')]

Scenario: There is this web page which has a list of 10 web link. Click on each web link and open in new window or tab using selenium Java [duplicate]

This question already has an answer here:
How to click on particular element in a list using selenium webdriver?
(1 answer)
Closed 4 years ago.
I got this as an interview question.
Need help to solve this
Scenario: There is this web page which has a list of 10 web link. Click on each web link and open in new window or tab using selenium Java .
Example here.
Click on all tutorial from WebDriver Tutorial. which should open in a new tab
As per your response in comment section, you can achieve the same behavior through Actions class which is available in selenium.
You can try out this code :
public class Amisha {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user***\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.guru99.com/selenium-tutorial.html");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,650)", "");
List<WebElement> element = driver.findElements(By.xpath("//strong[text()='WebDriver Tutorial']/following-sibling::table[1]/descendant::a"));
Actions action = new Actions(driver);
for(WebElement ele:element) {
action.keyDown(Keys.LEFT_CONTROL).moveToElement(ele).click().keyUp(Keys.LEFT_CONTROL).build().perform();
}
}
}
you can achieve this using the JavascriptExecutor
First, Capture all the required link element in list
Iterate all the list element and get the href value from the anchor tag
Open the window using the JavaScript executor by passing the above href value
Code:
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.guru99.com/selenium-tutorial.html");
driver.manage().window().maximize();
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Selenium Tutorial"));
List<WebElement> tutorialLinkList=driver.findElements(By.xpath("//strong[contains(text(),'Tutorial')]/ancestor::a"));
JavascriptExecutor js=(JavascriptExecutor)driver;
//I have just clicked only 10 link. If you want to iterate all the available links, then use foreach loop
for(int i=0;i<10;i++){
String url=tutorialLinkList.get(i).getAttribute("href");
js.executeScript("window.open(arguments[0])",url); //New Tab will be opened
}
}
Note: Here, I have opened only the first 10 links in different tab. If you wish to open all the link in new tab,then I would suggest to use foreach loop as below
for(WebElement tutoialLink : tutorialLinkList){
String url=tutoialLink.getAttribute("href");
js.executeScript("window.open(arguments[0])",url); //New Tab will be opened
}
Edit: Code with Actions Class
It looks right click is not working in that URL and hence, you can open the link is new tab by performing Ctr + click action as below
public static void main(String args[]) {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://www.guru99.com/selenium-tutorial.html");
driver.manage().window().maximize();
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Selenium Tutorial"));
List<WebElement> tutorialLinkList=driver.findElements(By.xpath("//strong[contains(text(),'Tutorial')]/ancestor::a"));
Actions action = new Actions(driver);
//I have just clicked only 10 link. If you want to iterate all the available links, then use foreach loop
for(int i=0;i<10;i++){
action.keyDown(Keys.CONTROL).click(tutorialLinkList.get(i)).keyUp(Keys.CONTROL).build().perform();
}
}

how to loop list of webelements using java and selenium web driver?

Hii can any one tell me how to loop a list of web elements using java and selenium web driver
here is my code
these are the objects
By ProjectSummaryReport_Campaign = By.name("q.a.62.d");
By ProjectSummaryReport_ProjectTitle = By.name("q.a.1.d");
By ProjectSummaryReport_ProjectAllocation = By.name("q.a.63.d");
By ProjectSummaryReport_JobNumber = By.name("q.a.2.d");
By ProjectSummaryReport_ArchivalStatus = By.name("q.a.6.d");
By ProjectSummaryReport_StartDate = By.name("q.a.7.d");
By ProjectSummaryReport_EndDate = By.name("q.a.8.d");
this is the code
Wrappers.Click(ProjectSummaryReport_Campaign);
Wrappers.Click(ProjectSummaryReport_ProjectTitle);
Wrappers.Click(ProjectSummaryReport_ProjectAllocation);
Wrappers.Click(ProjectSummaryReport_JobNumber);
Wrappers.Click(ProjectSummaryReport_ArchivalStatus);
Wrappers.Click(ProjectSummaryReport_StartDate);
Wrappers.Click(ProjectSummaryReport_EndDate);
Click_Link method
public static void Click(By byobj) {
_driver.findElement(byobj).click();
}
please dont mined if any thing is wrong I am very new to this selenium automation thanks is advance for solutions
you meant smthing like this?
List<WebElement> list = Arrays.asList(WebElement, WebElement1, WebElement2...);
for(WebElement el : list){
el.click();
}

Clicking on link one by one from the same page using selenium webdriver

I'm trying to click on state link given url then print title of next page and go back, then click another state link dynamically using for loop. But loop stops after initial value.
My code is as below:
public class Allstatetitleclick {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.adspapa.com/");
WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
List<WebElement> catValues = catBox.findElements(By.tagName("a"));
System.out.println(catValues.size());
for(int i=0;i<catValues.size();i++){
//System.out.println(catValues.get(i).getText());
catValues.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
}
System.out.println("TEST");
}
}
The problem is after navigating back the elements found previously will be expired. Hence we need to update the code to refind the elements after navigate back.
Update the code below :
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.adspapa.com/");
WebElement catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
List<WebElement> catValues = catBox.findElements(By.tagName("a"));
for(int i=0;i<catValues.size();i++)
{
catValues.get(i).click();
System.out.println(driver.getTitle());
driver.navigate().back();
catBox = driver.findElement(By.xpath("html/body/table[1]/tbody/tr/td/table/tbody/tr/td[1]/table"));
catValues = catBox.findElements(By.tagName("a"));
}
driver.quit();
I have tested above code at my end and its working fine.You can improve the above code as per your use.
Note: I have executed this and its working fine now.It will give you the size and clicking on every link.It was a issue where you need to go inside the Frame.
It has a Frame where you need to switch.
Please copy and paste and execute it.
Hope you find your answer.

Categories

Resources