How to click on the image through Selenium using Python

时间:2019-01-18 18:28:46

标签: python selenium xpath css-selectors webdriverwait

I've been trying to select one image tag, however, since it doesn't have any name and id I'm having trouble while doing the same.

HTML:

<tr __gwt_row="0" __gwt_subrow="0" class="GPBYFDECG">
<td class="GPBYFDEBG GPBYFDEDG GPBYFDEEG datagridCellStyle">
    <div style="outline-style:none;" __gwt_cell="cell-gwt-uid-29">
        ACD DETAILS NEW
    </div>
</td>
<td class="GPBYFDEBG GPBYFDEDG datagridCellStyle">
    <div style="outline-style:none;" __gwt_cell="cell-gwt-uid-30">
        ACD Details
    </div>
</td>
<td class="GPBYFDEBG GPBYFDEDG GPBYFDEOG datagridCellStyle">
    <div style="outline-style:none;" __gwt_cell="cell-gwt-uid-31" tabindex="0">


        //IMAGE THAT I NEED TO SELECT AND CLICK
        <img onload="this.__gwtLastUnhandledEvent=&quot;load&quot;;" src="http://172.00.00.00:8080/demoreports/DemoReportsApp/clear.cache.gif" style="width:25px;height:23px;background:url(http://172.00.00.00:8080/demoreport/DemoReportsApp/0210CFCB6CBE82D7E9FAC82D9F901495.cache.png) no-repeat -333px 0px;" border="0">
    </div>
</td>

Code:

driver.find_element_by_xpath('//img[@onload="this.__gwtLastUnhandledEvent=&quot;load&quot;;"]').click()

Above code doesn't work. Is there any other way, I can click() on this img as it generates javscript rendered reports.

1 个答案:

答案 0 :(得分:0)

所需元素是动态元素,因此您必须为所需 ElementToBeClickable 引入 WebDriverWait ,并且可以使用以下Locator Strategies作为解决方案之一:

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "td.datagridCellStyle img[onload*='gwtLastUnhandledEvent'][src*='demoreports/DemoReportsApp/clear']"))).click()
    
  • 使用XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[contains(@class, 'datagridCellStyle')]//img[contains(@onload, 'gwtLastUnhandledEvent') and contains(@src, 'demoreports/DemoReportsApp/clear')]"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC