如何使用硒Python单击img按钮

问题描述 投票:1回答:1

我正在尝试访问Selenium中的以下类,但它显示未找到元素错误。

HTML

<button class="gpquestion-plusicon">
  <img src="./assets/images/viewdetails.png">
</button>

代码

driver.find_elements_by_css_selector("//img[@src='./assets/images/viewdetails.png']").click()

driver.find_element_by_css_selector("//img[@src='./assets/images/viewdetails.png']").click()
driver.find_elements_by_xpath("//img[@src='./assets/images/viewdetails.png']").click()

例外

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: 
An invalid or illegal selector was specified

不幸的是,它们都不起作用。 xpath显示未找到任何元素错误。

有什么建议吗?

image selenium xpath src
1个回答
0
投票

您正在尝试将xpath用作css_selector。尝试

driver.find_element_by_css_selector("[src='./assets/images/viewdetails.png']").click()

driver.find_element_by_xpath("//img[@src='./assets/images/viewdetails.png']").click()

您也可以使用显式等待

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

wait = WebDriverWait(driver, 10)
wait.until(ec.element_to_be_clickable((By.CSS_SELECTOR, "[src='./assets/images/viewdetails.png']"))).click()
# or
wait.until(ec.element_to_be_clickable((By.XPATH, "//img[@src='./assets/images/viewdetails.png']"))).click()
© www.soinside.com 2019 - 2024. All rights reserved.