Capturing and moving all links on a web page
An iterator and an advanced for loop can do the same job; However, inconsistencies in page navigation in a loop can be resolved using the concept of an array.
private static String[] links = null; private static int linksCount = 0; driver.get("www.xyz.com"); List<WebElement> linksize = driver.findElements(By.tagName("a")); linksCount = linksize.size(); System.out.println("Total no of links Available: "+linksCount); links= new String[linksCount]; System.out.println("List of links Available: ");
1 | Capturing all links under a specific frame | class | id and move one by one
driver.get("www.xyz.com"); WebElement element = driver.findElement(By.id(Value)); List<WebElement> elements = element.findElements(By.tagName("a")); int sizeOfAllLinks = elements.size(); System.out.println(sizeOfAllLinks); for(int i=0; i<sizeOfAllLinks ;i++) { System.out.println(elements.get(i).getAttribute("href")); } for (int index=0; index<sizeOfAllLinks; index++ ) { getElementWithIndex(By.tagName("a"), index).click(); driver.navigate().back(); } public WebElement getElementWithIndex(By by, int index) { WebElement element = driver.findElement(By.id(Value)); List<WebElement> elements = element.findElements(By.tagName("a")); return elements.get(index); }
2 | Capturing all links [Alternative Method]
Java
driver.get(baseUrl + "https://www.google.co.in"); List<WebElement> all_links_webpage = driver.findElements(By.tagName("a")); System.out.println("Total no of links Available: " + all_links_webpage.size()); int k = all_links_webpage.size(); System.out.println("List of links Available: "); for(int i=0;i<k;i++) { if(all_links_webpage.get(i).getAttribute("href").contains("google")) { String link = all_links_webpage.get(i).getAttribute("href"); System.out.println(link); } }
Python
from selenium import webdriver driver = webdriver.Firefox() driver.get("https://www.google.co.in/") list_links = driver.find_elements_by_tag_name('a') for i in list_links: print i.get_attribute('href') driver.quit()
source share