2024-05-23 17:31:08 发布
网友
我想断言一个图像出现在页面上。 我在python中使用selenium web驱动程序。 我还想在图像尚未加载时打印消息。 谁能帮我写剧本吗?在
以下是在网站上显示图像的html代码: [img src='照片.jpg'class='image class']
可能有更好的方法来完成这个任务,但是我决定检索所有的图像标记。在
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))
我不能帮助使用python,但是可以为那些希望用Java做类似事情的人提供一个一般性的建议和Java代码。我的方法是
src
HTTP GET
200 OK
naturalWidth
.complete
下面是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(); } }
忽略了驱动程序设置,但这应该是工作一旦你加入你的。部分归功于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)
可能有更好的方法来完成这个任务,但是我决定检索所有的图像标记。在
我不能帮助使用python,但是可以为那些希望用Java做类似事情的人提供一个一般性的建议和Java代码。我的方法是
src
属性并快速生成HTTP GET
打电话并确保得到200 OK
响应。在naturalWidth
属性 Javascript。如果大于0,则渲染良好。然而,这 在IE中的工作方式不同。IE具有.complete
属性。会的 如果渲染图像,则为true(引用here)下面是Java代码示例
忽略了驱动程序设置,但这应该是工作一旦你加入你的。部分归功于Nilesh用他的Java示例为我指明了正确的方向。在
相关问题 更多 >
编程相关推荐