How can I get the 10th item of the <li> elements in an <ul> with Selenium using Python?

Question:

I want to get the 10th value ie. value of Price/Book of the 10th <li> in an <ul>.

enter image description here

I have tried following ways but those didn’t work. Instead of 10th element every time I am getting the first element.

block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]/li[10]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]/li[position()=10]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_element(by=By.XPATH, value="//li[10][contains(@class, 'snap-panel')]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_element(by=By.XPATH, value="//li[position()=10][contains(@class, 'snap-panel')]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_elements(by=By.XPATH, value="//li[contains(@class, 'snap-panel')]")
for item in block:
    name = item.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-name')]").text
    if 'Price/Book' in name:
        value = item.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text

How can I get the 10th element?

Asked By: Apurba Roy

||

Answers:

To get the nth element, there’s a CSS selector for that!

Use the nth-of-tye CSS selector:

li:nth-of-type(10)

For example, in your case:

driver.find_element_by_css_selector("li:nth-of-type(10)").click()

This will find the 10th <li> tag.

You can also combine it with other CSS selectors to narrow down your search, for example, your CSS Selector can be:

li:nth-of-type(10) .CLASS-NAME

the . is for selecting a CSS class.

See also

CSS selectors (w3schools)

Answered By: MendelG

You can get the dp-value of 10th <li> using the below XPATH:

value = (.//ul[@class='small-block-grid-3 large-block-grid-4 sal-component-band-grid']/li)[10]//div[@class='dp-value'].text
Answered By: AbiSaran