【问题标题】:Unable to click an image using selenium无法使用硒单击图像
【发布时间】:2013-12-01 14:41:16
【问题描述】:

我有下面的 HTML,请帮助我编写一个 java 代码来点击“Patient”按钮。

<span id="addPat">
  <span style="cursor: hand;" onclick="javascript:AddPatient();">   
    <img width="17" height="17" class="btnRowIcon" src="../Images/V10Icons/Add.gif"/>

【问题讨论】:

    标签: java selenium internet-explorer-10


    【解决方案1】:

    您必须以某种方式确定跨度;可能看起来像这样:

    WebElement patientButton = driver.findElement(By.xpath("//span/span[child::img[@class='btnRowIcon']]"));
    

    根据您网站的结构,这可能有效,也可能无效。一旦你有了这个元素,你可以用patientButton.click()点击它。

    【讨论】:

    • 我用过:idriver.findElement(By.cssSelector("span#id img.btnRowIcon")).click();但它不起作用 -
    • 硒找到了正确的元素吗?尝试打印idriver.findElement(By.cssSelector("span#id img.btnRowIcon")).getAttribute("onclick") 的值,看看这是否是预期的"javascript:AddPatient();"。另外,如果手动单击,这是否按预期工作?
    • 我使用了以下方法,它起作用了:JavascriptExecutor js; js = (JavascriptExecutor)idriver; js.executeScript("javascript:AddPatient();");
    【解决方案2】:

    我同意 sircapsalot,您也可以使用 implicit or explicit waits..
    等待元素的存在 这是一个使用显式等待的示例

    WebDriverWait image = new WebDriverWait(driver,60); 
    image.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span#id img.btnRowIcon")));
    image.click();   
    

    上面的代码会等待60秒让图片可见,

    • 如果在60之前找到图像将被点击,否则将引发异常..

    【讨论】:

      【解决方案3】:

      blalasaadri 的答案的更好选择是使用 CSS 选择器。 They are faster, cleaner,而且……更好。

      WebElement image = driver.findElement(By.cssSelector("span#addPat img.btnRowIcon"));
      // now you can perform what you want to on the image. image.getAttribute("src")...
      

      【讨论】:

      • 我用过:idriver.findElement(By.cssSelector("span#id img.btnRowIcon")).click();但它不工作
      • 哦废话.. .对不起.. 菜鸟错误。这是span#addPat img.btnRowIcon
      • 我使用了以下方法,它起作用了:JavascriptExecutor js; js = (JavascriptExecutor)idriver; js.executeScript("javascript:AddPatient();");
      猜你喜欢
      • 2017-10-20
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多