2016-04-22 112 views
0

我想获取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(); 
} 
} 
+0

你忘记你的代码:_D – fabersky

+0

@fabesky我刚刚添加。以前无法添加格式问题。 –

回答

0

您的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)]")); 
+0

谢谢@Buaban的答案。但在使用你提到的两个xpath后,列表返回的项目数量为0. –

+0

@amlandey你能用最新的代码更新这个问题吗?我确定我的Xpath是正确的,所以问题可能在另一行。 – Buaban

+0

@amlandey我已将代码添加到我的答案中。您无需获取Block,只需一次获取链接。 – Buaban

0
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(); 
} 
}