Search code examples
pythonseleniumgetattributes

filter get_attribute for item results


Currently I'm using get_attribute to get all the instances of data-id on the page as soon as they load. But what I'm trying to figure out is how I could filter out some of these results. Particularly the ones with certain values for their data-type attribute. Is there anyway I could do this?

ids = [item.get_attribute('data-id') for item in WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[data-id]")))]


Solution

  • You could add a if condition to your list comprehension :

    if item.get_attribute('data-type') == "yourValue"
    

    It would then look like this:

    els = WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "[data-id]")))
    ids = [item.get_attribute('data-id') 
           for item in els if item.get_attribute('data-type') == "yourValue"]
    

    EDIT:
    The value of item.get_attribute('data-type') is not "Knife" but "Knife ". (space at the end)

    Solution1: Remove the whitespaces using strip():

    if item.get_attribute('data-type').strip() == "Knife"
    

    Solution2: use in

     if "Knife" in item.get_attribute('data-type')
    

    Solution3: add a space!

    if item.get_attribute('data-type') == "Knife "
    

    EDIT2: If you want to match multiple values use:

    accepted_type = ("Knife", "Knife2",...)
    if item.get_attribute('data-type').strip() in accepted_type