2016-09-14 70 views
0

这是网页的HTML代码来执行点击()这个超级链接:如何使用硒3

<a href="default_Usuario.asp?i=1"><img src="resources/v3_presioneaqui.gif" border="0"></a> 

我试着用这个代码:

driver.findElement(By.xpath("//a[@href ='default_Usuario.asp?i=1']")).click(); 

,但它并没有为我工作给出错误NoSuchElementException异常

+0

试试这个XPath'.//a[@href='default_Usuario.asp?i=1' ]/img' – Sudeepthi

回答

0

但它并没有对我的工作给予错误NoSuchElementException异常

有可能是以下原因造成的exception如下: -

  • 可能是你想定位定位元素不正确,您正在使用查找可能会动态更改的href属性的确切值。你应该有部分匹配尝试使用cssSelector为: -

    driver.findElement(By.cssSelector("a[href*='default_Usuario']")).click(); 
    
  • 可能是当你要寻找的元素,它不会出现在DOM,所以你应该实现WebDriverWait等到元素DOM可见和可点击如下: -

    WebDriverWait wait = new WebDriverWait(driver, 10); 
    WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href*='default_Usuario']"))); 
    el.click(); 
    
  • 可能这个元件是任何frame/iframe内部。如果是,你需要切换这frame/iframe发现如下所需的元素之前: -

    WebDriverWait wait = new WebDriverWait(driver, 10); 
    
    //Wait until frame/iframe to available and then switch to it 
    wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name")); 
    
    //Now find the desired element 
    WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("a[href*='default_Usuario']"))); 
    el.click(); 
    
    //Once all your stuff done with this frame/iframe need to switch back to default for further stuff 
    driver.switchTo().defaultContent(); 
    
+1

非常感谢,这解决了我的问题。 – Parth

+0

如果此答案需要[接受此答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)以及.. –

0

你应该尝试这样一个更广泛的选择:

//a[contains(@href, 'default_Usuario')]