如何验证jpg是否使用Selenium在页面上显示?

时间:2016-06-04 19:14:58

标签: python selenium firefox

使用python,selenium和firefox。我点击主页上的链接,它直接导致加载的JPG文件。我只想验证图像是否加载。图像的HTML是这样的:

<img src="https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%20Chart.jpg" alt="https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%20Chart.jpg">

我正在尝试使用xpath来定位元素:

def wait_for_element_visibility(self, waitTime, locatorMode, Locator):
     element = None
     if   locatorMode == LocatorMode.XPATH:
          element = WebDriverWait(self.driver, waitTime).\
                until(EC.visibility_of_element_located((By.XPATH, Locator)))
     else:
         raise Exception("Unsupported locator strategy.")
     return element

使用这本词典:

OrganizationalChartPageMap = dict(OrganizationalChartPictureXpath = "//img[contains(@src, 'Chart.jpg')]",                                 
)

这是我正在运行的代码:

def _verify_page(self):
    try:
      self.wait_for_element_visibility(20, 
                                     "xpath", 
                                     OrganizationalChartPageMap['OrganizationalChartPictureXpath']
      )
    except:   
      raise IncorrectPageException

我每次都会抛出errorspageexception。我做错了吗?有没有更好的方法来使用硒来验证图像?

编辑:这是元素的DOM:

enter image description here

1 个答案:

答案 0 :(得分:1)

附加alt值应该在xpath中工作,建议您将字典更改为:

= dict(OrganizationalChartPictureXpath = "//img[@alt='https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%20Chart.jpg' and contains(@src, 'Chart.jpg')]"

OR

或者使用src中图像的完整路径作为:

= dict(OrganizationalChartPictureXpath = "//img[@src='https://www.treasury.gov/about/organizational-structure/ig/Agency%20Documents/Organizational%20Chart.jpg']"

编辑: 根据图像中共享的DOM,您还可以使用img的类,它将成为您项目中的相应代码:

element = driver.find_element_by_class_name('shrinkToFit')