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')
2
Answers
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,
You can change
get_property
toget_attribute
by your needs or just get needed property directly.You can try it there:
Use this XPath for inclusive 3 and 10:
Or this XPath for exclusive 3 and 10: