How to use Selenium to find the last li in ul? or What's the best way to find the last li in ul using

16 Replies, 1461 Views

Hey everyone!

Struggling a bit here—trying to selenium find last li in ul but not getting it right. Tried a few things like `driver.find_elements_by_xpath("//ul/li")[-1]`, but it feels kinda hacky.

Is there a cleaner way? Maybe with CSS selectors or something more reliable?

Also, what if the list updates dynamically? Would love some tips or your go-to methods for this.

Thanks in advance! 🙌

(PS: If you’ve got a snippet, even better—my brain’s fried from trial and error lol.)
Hey! For selenium find last li in ul, you could try using CSS with `:last-child`. Like this:

`driver.find_element_by_css_selector("ul li:last-child")`

Way cleaner than XPath, imo.

If the list updates dynamically, maybe add a WebDriverWait to ensure the element is there before grabbing it.
XPath can be messy, but you could also do:

`//ul/li[last()]`

That’s the proper XPath way to get the last li.

For dynamic lists, wrap it in a wait like `WebDriverWait(driver, 10).until(...)` to avoid flakiness.
Dude, I feel you. Selenium find last li in ul is one of those things that seems simple but trips you up.

Try this:

```python
last_li = driver.execute_script("return document.querySelector('ul li:last-child')")
```

JS might be more reliable if the DOM’s being funky.
CSS selectors are def cleaner for this.

`ul > li:last-of-type`

Works like a charm.

For dynamic content, maybe throw in a `presence_of_element_located` wait.
You could also use `ul li:nth-last-child(1)`—same as `:last-child` but feels fancier lol.

For dynamic stuff, explicit waits are your best friend.

---

Hey, thanks everyone! The `:last-child` CSS selector worked perfectly.

One follow-up though—what if the `ul` has nested lists? Would `ul > li:last-child` still grab the right one, or do I need to adjust?

Also, big shoutout for the WebDriverWait tips—totally saved me from race conditions. 🙏
If you’re stuck on selenium find last li in ul, check out the `:-soup-selector` in BeautifulSoup if you’re parsing static HTML.

But for Selenium, stick with `:last-child` or XPath `last()`.

Also, Chrome DevTools can help verify your selectors before coding.
For dynamic lists, you might wanna poll for changes. Something like:

```python
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
last_li = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "ul li:last-child")))
```

Works like a charm for me.
Honestly, your XPath hack isn’t *that* bad. But yeah, `:last-child` is cleaner.

If the list’s super dynamic, maybe even check for `li` count first with `len(driver.find_elements_by_css_selector("ul li"))` to be safe.



Users browsing this thread: 2 Guest(s)