简体   繁体   中英

Unable to find gif image by Xpath/classname/cssSelector using selenium webdriver java

I am trying to locate image using Selenium webdriver but unable to locate it by Xpath/cssSelector

I have tried cssSelector and xpath but not working.

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

By cssSelector -->

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

By Xpath -->

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

I need to locate the image.

Snapshot of the page source:

详细页面来源

Your image resides within an iframe

在此处输入图片说明

So you will need to execute driver.switchTo() function prior to attempting to locate element which is inside the iframe.

Once done you should be able to use the XPath expression like:

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

To click() on the image, as the the desired element is within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt .
  • Induce WebDriverWait for the desired elementToBeClickable .
  • You can use either of the following 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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM