如何使用 Selenium Python 通过已知的 src 属性查找元素

How to find an element by a known src attribute using Selenium Python

我正在尝试通过将 Selenium 与 python 结合使用,通过 src 属性的已知值来查找元素。元素是Google地图中某个位置地址左边的点图。

即 html 我要尝试的元素 select:

<img alt="" jstcache="935" src="//www.gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp.png" class="Liguzb" jsan="7.Liguzb,0.alt,8.src">

我如何 select 通过使用 link:

搜索给定的元素
www.gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp.png

谢谢。

要将元素定位为您知道的 src 属性值,您可以使用以下任一方法 :

  • 使用css_selector:

    element = driver.find_element(By.CSS_SELECTOR, "img.Liguzb[src*='gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp']")
    
  • 使用 xpath:

    element = driver.find_element(By.XPATH, "//img[@class='Liguzb' and contains(@src, 'gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp')]")
    

定位 visible 元素而不是 you need to induce WebDriverWait for the and you can use either of the following :

  • 使用CSS_SELECTOR:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img.Liguzb[src*='gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp']")))
    
  • 使用 XPATH:

    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='Liguzb' and contains(@src, 'gstatic.com/images/icons/material/system_gm/1x/place_gm_blue_24dp')]")))
    
  • 注意:您必须添加以下导入:

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