如何使用Selenium和Python单击<img/>标记以展开“树视图”

时间:2019-02-26 04:44:56

标签: python selenium xpath css-selectors webdriverwait

这是我要对其执行点击操作的标记。元素成功定位,也接受click()事件,但未执行任何操作。

<img class="pointer" id="id53" src="/images/tree/elbow-minus.gif" alt="collapse not last" onclick="$(this)[0].src='/images/ajax-indicator.gif';var wcall=wicketAjaxGet('wicket/page?1-1.IBehaviorListener.0-dashboardBody-columns-0-gadgets-1-body-content-treeTable-form-rows-4-expandLink',function() { }.bind(this),function() { }.bind(this), function() {return Wicket.$('id53') != null;}.bind(this));;return !wcall;">

代码:

link_xpath = "//a[contains(text(),'git')]//parent::*/img"
driver.find_element_by_xpath(link_xpath).click()

1 个答案:

答案 0 :(得分:0)

根据您提供的HTML,它是一个<img>标签,并且该元素是动态元素。因此,要单击所需的元素,必须诱使 WebDriverWait 使元素可点击,并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "img.pointer[src='/images/tree/elbow-minus.gif']"))).click()
    
  • 使用XPATH

    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//img[@class='pointer' and @src='/images/tree/elbow-minus.gif']"))).click()
    
  • 注意:您必须添加以下导入:

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