简体   繁体   中英

How do I get to this element in Python Selenium

I'm trying to select this element with Python Selenium, but don't know how since it does not contain and id/class name/etc..

Here is the HTML:

<img src="/resource/1599091587000/nforce__SLDS0102/assets/icons/utility/chevrondown_60.png">

I've tried:

chrome_browser.find_element_by_xpath("//img[contains(text(),'/resource/1599091587000/nforce__SLDS0102/assets/icons/utility/chevrondown_60.png')]")

Since text() searches for the inner text for the HTML tag, you should not use that to search for this particular element since the URL is in the src attribute.

You may search it using the src attribute

//img[@src='/resource/1599091587000/nforce__SLDS0102/assets/icons/utility/chevrondown_60.png')]

or just a part of it using

//img[contains(@src,'chevrondown_60')]

The element seems to be a dynamic element. So to locate the element you can use either of the following Locator Strategies :

  • Using css_selector :

     element = chrome_browser.find_element_by_css_selector("img[src^='/resource'][src$='assets/icons/utility/chevrondown_60.png']")
  • Using xpath :

     element = chrome_browser.find_element_by_xpath("//img[starts-with(@src, '/resource') and contains(@src, 'assets/icons/utility/chevrondown_60.png')]")

Ideally, to locate the element you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies :

  • Using CSS_SELECTOR :

     element = WebDriverWait(chrome_browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img[src^='/resource'][src$='assets/icons/utility/chevrondown_60.png']")))
  • Using XPATH :

     element = WebDriverWait(chrome_browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[starts-with(@src, '/resource') and contains(@src, 'assets/icons/utility/chevrondown_60.png')]")))
  • Note : You have to add the following imports:

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

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