[英]Not able to click all links on a web page using Java and Selenium Webdriver
[英]How to click on specific link after extracting all the links from a web page in selenium webdriver
我是自動化世界的新手,致力於自動化 BBC 網站。 我有很多鏈接,還有鏈接中的文本。 . 我想單擊帶有“輔助功能幫助”文本的特定鏈接。 請告知我該怎么做。 以下是我的代碼:
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BBC_AllLinks {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
driver.get("http://www.bbc.com");
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
//Total number of links in the webpage
System.out.println("Total Links--> "+allLinks.size());
//35th index
Thread.sleep(4000);
for (int i =0; i<=allLinks.size();i++)
System.out.println(allLinks.get(i).getText()+"----"+allLinks.get(i).isDisplayed());
}
}
您可以使用 Xpath 直接單擊具有特定文本內容的鏈接,如下所示(未經測試的代碼):
driver.findElement(By.xpath("//a[contains(text(), \"Accessibility Help\")]")).click();
請注意,如果此文本有多個鏈接,它將嘗試單擊第一個滿足文檔順序條件的鏈接。 一般來說,如果可能的話,最好用 id 或唯一的 CSS 選擇器來標識元素。
您還可以遍歷您手動擁有的 Web 元素列表並檢查其中的文本(通過getText() 之類的方法)並單擊自己。
我對你的代碼應該做什么感到困惑。 您是否嘗試記錄頁面上的所有鏈接,然后單擊該鏈接? 或者你只是想點擊鏈接?
如果您要做的只是單擊該鏈接,那么這就是您所需要的。
driver.findElement(By.linkText("Accessibility Help")).click();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.