Search code examples
pythonseleniumxpathcss-selectorswebdriverwait

Selenium - find id based on class tag


I want to find with Selenium (python) an id based on a class tag

I want to find the result of a html form. There are 2 results possible, available or not available. Both options will appear in the html code, but two different CSS format will be used to show the result and to hide the other option.

HTML CODE

I would like to get the id (either "WarningDisponible" or "WarningIndisponible") based on the div class "Content Warning" (this is the result), "Content Warning hidden" is not the result.


Solution

  • To print the value of the id attribute i.e. WarningIndisponible based on the classname Content warning you can use either of the following Locator Strategies:

    • Using css_selector:

      print(driver.find_element(By.CSS_SELECTOR, "div.Content.warning > p").get_attribute("id"))
      
    • Using xpath:

      print(driver.find_element(By.XPATH, "//div[@class='Content warning']/p").get_attribute("id"))
      

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

    • Using CSS_SELECTOR:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.Content.warning > p"))).get_attribute("id"))
      
    • Using XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='Content warning']/p"))).get_attribute("id"))
      
    • 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