如何在Selenium WebDriver中单击网页中的所有链接 [英] How to click on All links in web page in Selenium WebDriver
问题描述
我有10个不同的页面,其中包含不同的链接.如何点击所有链接?
I have 10 different pages contain different links. How to click on all the links?
条件是: 我)我不知道有多少个链接 ii)我要计算并单击每个链接
Conditions are : i) I don't know how many links are there ii) I want to count and click on each link
请向我建议Selenium WebDriver脚本.
Please suggest me Selenium WebDriver script.
推荐答案
捕获并浏览网页上的所有链接
迭代器和高级for循环可以完成类似的工作;但是,可以使用数组概念解决循环内页面导航的不一致.
Iterator and advanced for loop can do similar job; However, the inconsistency on page navigation within a loop can be solved using array concept.
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: ");
// print all the links from webpage
for(int i=0;i<linksCount;i++)
{
links[i] = linksize.get(i).getAttribute("href");
System.out.println(all_links_webpage.get(i).getAttribute("href"));
}
// navigate to each Link on the webpage
for(int i=0;i<linksCount;i++)
{
driver.navigate().to(links[i]);
Thread.sleep(3000);
}
1 |捕获特定frame | class | id下的所有链接,并逐一导航
1| Capture all links under specific frame|class|id and Navigate 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 |捕获所有链接[备用方法]
2| Capture all links [Alternate method]
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()
这篇关于如何在Selenium WebDriver中单击网页中的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!