如何断言selenium python web驱动程序中存在的图像



我想断言页面上存在图像。我在python中使用selenium web驱动程序。我还希望在图像尚未加载时打印一条消息。有人能帮我写剧本吗?

下面是一段在网站上显示图像的html代码:[img src='photo.jpg'class='image class']

我对python无能为力,但可以为那些希望在Java中做类似事情的人提供一个一般建议和Java代码。我的方法是

  1. 获取图像的src属性并快速生成HTTP GET打电话确认收到200 OK回复
  2. 一旦完成,你可以使用检查WebElement的naturalWidth属性Javascript。如果大于0,则其渲染良好。然而IE的工作方式不同。IE具有.complete属性。它将是如果渲染图像,则为true(此处参考(

以下是示例Java代码

@Test
   public void test()
   {
      WebDriver driver = new FirefoxDriver();
      String url = "http://www.espncricinfo.com/";
      driver.get(url);
      WebElement img = driver.findElement(By.cssSelector("a[title='ESPN Cricinfo']>img"));
      String src = img.getAttribute("src");
      Client client = Client.create();
      WebResource resource = client.resource(src);
      assertThat("Response code is not 200 OK", resource.get(ClientResponse.class).getStatus(), equalTo(200));
      assertThat("Image is not rendered correctly", isImageVisible(driver, img),equalTo(true));
      driver.quit();
   }
   public boolean isImageVisible(WebDriver driver, WebElement image)
   {
      Boolean result = null;
      if (driver instanceof InternetExplorerDriver || ((RemoteWebDriver) driver).getCapabilities().getBrowserName().equals("internet explorer"))
      {
         result = (Boolean) ((JavascriptExecutor) driver).executeScript("return arguments[0].complete;", image);
      }
      else
      { //other browser types use diff method to check
         result = (Boolean) ((JavascriptExecutor) driver).executeScript("return (typeof arguments[0].naturalWidth!="undefined" && arguments[0].naturalWidth>0);", image);
      }
      return result.booleanValue();
   }
}

可能有更好的方法,但我决定检索所有的图像标记。

all_images = self.driver.execute_script("return document.getElementsByTagName('img')")
for image in range(0, len(all_images)):
    print self.driver.execute_script("return document.getElementsByTagName('img')[{}].src".format(image))

省略了驱动程序设置,但一旦添加了您的驱动程序,这应该会起作用。部分归功于Nilesh用他的Java示例为我指明了正确的方向。

import requests
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
def setUp(self):
    self.verificationErrors = []

def test_images_for_200_response(self):
    driver.get('http:example.com')
    example_images = driver.find_elements(By.TAG_NAME, 'img')
    for image in example_images:
        current_link = image.get_attribute("src")
        r = requests.get(current_link)
        try: self.assertEqual(r.status_code, 200)
        except AssertionError, e: self.verificationErrors.append(current_link + ' delivered response code of ' + r.status_code)
def tearDown(self):
    driver.quit()
    self.assertEqual([], self.verificationErrors)

相关内容

  • 没有找到相关文章

最新更新