【问题标题】:Unable to identify image using WebDriver as it gives null value无法使用 WebDriver 识别图像,因为它提供空值
【发布时间】:2018-01-10 02:46:42
【问题描述】:

当我搜索图像的 src 属性时,我得到了 null。请解析图像的元素标识。

我的 Selenium WebDriver 代码使用 WebDriver 识别图像 src:

@FindBy(xpath = "//div[contains(@class, 'image-section')]/img")
private WebElement getimage;

public String getImageSrc(){
    return  getimage.getAttribute("src");
}

我有以下异常:

org.openqa.selenium.NoSuchElementException: no such element:

【问题讨论】:

  • 您认为有人可以如何帮助您处理这些信息?您的异常意味着您无法找到感兴趣的元素。
  • 这是图像的 HTML:

标签: selenium webdriver


【解决方案1】:

如果这是你的 html:

<div class="image-section">
<div class="img-container">
<img alt="Test Alternate text" src="/content/dam/kh-facebook-group-cover- photo-size.png">

你可以试试这个 xpath 来定位元素:

//div[@class='image-section']/div[@class='img-container']/img[@alt='Test Alternate text']

之后得到"src"属性。

【讨论】:

    【解决方案2】:

    根据您在问题下方的评论,您可以使用任何 xpaths

    //img[@alt='Test Alternate text']
    
    //img[@alt='Test Alternate text' and @src='/content/dam/kh-facebook-group-cover- photo-size.png']
    

    //div[@class='img-container']/img[@alt='Test Alternate text' and @src='/content/dam/kh-facebook-group-cover- photo-size.png']
    

    【讨论】:

      【解决方案3】:

      您的 HTML:

      <div class="image-section">
      <div class="img-container">
      <img alt="Test Alternate text" src="/content/dam/kh-facebook-group-cover- photo-size.png">
      

      怎么了:

      • img标签是第二个div标签

      解决它:

      @FindBy(xpath = "//div[contains(@class, 'image-section')]//img")
      private WebElement getimage;
      
      public String getImageSrc(){
          return  getimage.getAttribute("src");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-30
        相关资源
        最近更新 更多