如何区分selenium webdriver中的图像链接和href链接?
问题描述:
我想获取selenium webdriver中维基百科主页的链接名称。在主页的底部有一个表格,其中包含维基百科姊妹项目的链接,如媒体维基,元维基等。但运行代码后,我得到了24个链接。但在网页上只有12个链接。我的怀疑是它也在拍摄图像的链接。如何区分selenium webdriver中的图像链接和href链接?
包tcsWebmail;
import java.io.File;
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 WikiPediaLinks {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://en.wikipedia.org/wiki/Main_Page");
System.out.println(driver.getTitle());
WebElement Block=driver.findElement(By.xpath("//*[@id='mp-sister']/table//a[not(img)]"));
List<WebElement> Links= Block.findElements((By.tagName("a")));
System.out.println("Printing the no of items in block");
int i=0;
for (i=0;i<Links.size();i++){
System.out.println(Links.get(i).getText());
}
System.out.println("The no of items are"+Links.size());
driver.quit();
}
}
答
您的XPath包含您怀疑的图像。为了得到a
不包含后代img
,你可以使用下面的XPath:
//*[@id='mp-sister']/table//a[not(img)]
或
//*[@id='mp-sister']/table//a[not(descendant::*[local-name() = 'img'])]
下面
见代码:
List<WebElement> Links= driver.findElements(By.xpath("//*[@id='mp-sister']/table//a[not(img)]"));
答
In for loop put another condition to check to validate imgage (img) or link (href)
List<WebElement> Links= Block.findElements((By.tagName("a")));
System.out.println("Printing the no of items in block");
for (int i=0;i<Links.size();i++)
{
if(Links.get(i).getAttribute("href").contains("http://")
{System.out.println(Links.get(i).getText());
}
driver.quit();
}
}
你忘记你的代码:_D – fabersky
@fabesky我刚刚添加。以前无法添加格式问题。 –