skip to Main Content

I have a list of divs as follows

enter image description here

From the list of divs given below, I only want to extract certain data from divs between data-index=3 and data-index=10.

Currently I am able to extract all the divs using XPATH. But I don’t want that. I want to only target specific divs.

How do I do that? Thank you

2

Answers


  1. If you don’t want to use XPATH, you can loop through elements and filter attributes range that you expect to work with.

    For example,

    def extract_data_by_index_range(elements, start_index, end_index, prop):
    
        extracted_data = []
    
        for element in elements:
            data_index = element.get_attribute('data-index')
            if data_index is not None:
                data_index = int(data_index)
                if start_index <= data_index <= end_index:
                    extracted_data.append(element.get_property(prop))
    
        return extracted_data
    

    You can change get_property to get_attribute by your needs or just get needed property directly.

    You can try it there:

    url = "https://inputnum.w3spaces.com/saved-from-Tryit-2023-09-04.html"
    driver.get(url)
    divs = driver.find_elements(By.CSS_SELECTOR, 'div[data-index]')
    def extract_data_by_index_range(elements, start_index, end_index, prop):
    
        extracted_data = []
    
        for element in elements:
            data_index = element.get_attribute('data-index')
            if data_index is not None:
                data_index = int(data_index)
                if start_index <= data_index <= end_index:
                    extracted_data.append(element.get_property(prop))
    
        return extracted_data
    
    mapped_props = extract_data_by_index_range(divs, 3, 10, 'innerText')
    
    Login or Signup to reply.
  2. Use this XPath for inclusive 3 and 10:

    //div[div[@data-index]]/div[@data-index[. &gt;= 3 and . &lt;= 10]]
    

    Or this XPath for exclusive 3 and 10:

    //div[div[@data-index]]/div[@data-index[. &gt; 3 and . &lt; 10]]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search