无法使用Selenium WebDriver Java通过Xpath / classname / cssSelector查找gif图像

时间:2019-05-24 15:10:54

标签: java selenium-webdriver xpath css-selectors webdriverwait

我正在尝试使用Selenium Webdriver定位图像,但无法通过Xpath / cssSelector定位图像

我尝试了cssSelector和xpath,但是没有用。

<img alt="" class="i-amphtml-fill-content i-amphtml-replaced-content" decoding="async" src="https://tpc.googlesyndication.com/simgad/303052068860032968">

通过cssSelector->

WebElement elementOut = driver.findElement(By.cssSelector(".i-amphtml-fill-content.i-amphtml-replaced-content"));

通过Xpath->

WebElement elementOut = driver.findElement(By.xpath("//*[@id='aw0']/amp-img/img"));

我需要找到图片。

页面源快照:

Detailed page source

2 个答案:

答案 0 :(得分:1)

您的图片位于iframe

enter image description here

因此,在尝试定位iframe内的元素之前,您需要执行driver.switchTo()函数。

完成后,您应该可以像这样使用XPath expression

driver.findElement(By.xpath("//img[contains(@class,'replaced-content')]"));

答案 1 :(得分:0)

由于图像上的click()所需元素位于<iframe>中,因此您必须:

  • 为所需的 frameToBeAvailableAndSwitchToIt 诱导 WebDriverWait
  • 为所需的 elementToBeClickable 诱导 WebDriverWait
  • 您可以使用以下任一Locator Strategies

    • cssSelector

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[id$='com/Web/News24/Homepage_20'][name^='google_ads_iframe_'][title='3rd party ad content']")));
      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("img.i-amphtml-fill-content.i-amphtml-replaced-content[src^='https://tpc.googlesyndication.com/simgad']"))).click()
      
    • xpath

      new WebDriverWait(driver, 10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[contains(@id, 'com/Web/News24/Homepage_20') and starts-with(@name, 'google_ads_iframe_')][@title='3rd party ad content']")));
      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//img[@class='i-amphtml-fill-content i-amphtml-replaced-content' and starts-with(@src, 'https://tpc.googlesyndication.com/simgad')]"))).click();