finding items with selenium by CSS selector using multiple attributes
Selenium WebDriver - Finding Elements using cssSelector and nth child - Stack Overflow
Why is selenium finding xpath but not the css selector for an element?
CSS selectors and how to check if a web page has opened correctly, in python
You should look for a css selector tutorial. They're out there. You can select by id, name, classes, etc. Without looking at the HTML it's hard to help you out.
You other question: How to see if a web page has opened correctly is a bit vague. There is a "doneness" that selenium will wait for when the get command is done. Often times that's not enough for modern pages with asynchronus events and rendering. It's best to find an element that, to you, means the page is done loading all the needed data and "wait" for that element to be visible.
More on reddit.comVideos
Hi all. I'm trying to use Selenium to find an element by CSS selector and although I've tried using the documentation, I think I'm misunderstanding something.
This is what I'm trying:
driver.find_element(By.CSS_SELECTOR,f"img [src='images/icons/new.gif'][alt='Add new item to list']").click()
This is the element I want to find and click:
<img src="images/icons/new.gif" alt="Add new item to list">
The error I get is as follows:
Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"css selector","selector":"img [src='images/icons/new.gif'][alt='Add new item to list']"}I can see it's on the page, however, so I'm not sure what I'm missing. I can find other items using XPATH and ID so selenium is up and running, just to rule that out. Can anybody suggest anything?
(I'm using selenium 4.8.2 and python 3.11.1, if that helps)
You can generate the css-selector from ul like ul > li:nth-child(1) for home. See below:
driver.findElement(By.cssSelector("ul > li:nth-child(1)")); >> home
driver.findElement(By.cssSelector("ul > li:nth-child(2)")); >> posts
driver.findElement(By.cssSelector("ul > li:nth-child(3)")); >> events
also reachin span is the same:
driver.findElement(By.cssSelector("ul > li:nth-child(1) > a > span")); >> home
do you need css specifically? if not, you can also go for xpath, which imho reads better/clearer:
driver.findElement(By.xpath("(//span[@class='title'])[0]")); // home
driver.findElement(By.xpath("(//span[@class='title'])[1]")); // posts
...