Home > Software engineering >  Selenium - find id based on class tag
Selenium - find id based on class tag

Time:11-29

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.

Many thanks in advance!

CodePudding user response:

This website should help: https://selenium-python.readthedocs.io/locating-elements.html Search the div first with ContentWarning = driver.find_element_by_class_name('Content Warning') From there you can just search within the div by checking if ContentWarning.find_element_by_id('WarningDisponible') returns any results.

This does assume that there are no other elements in the HTML with the class name 'Content Warning' other than the div you are looking for.

CodePudding user response:

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
    
  • Related