You can get all the products by searching for the div tags that contain the attribute data-content="productItem". That is assuming each item has that attribute. From the screenshots you posted, it seems like that is the case.
You can accomplish this using find_elements_by_xpath()
for item in driver.find_elements_by_xpath('//div[@data-content="productItem"]'):
....
This would probably be the best way without having to worry about the elements having different css classes.
Answer from 010011100101 on Stack OverflowHi 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)
html - How to loop multiple elements in python selenium (different CSS selectors) - Stack Overflow
python - find_element_by_class_name for multiple classes - Stack Overflow
Selenium with Python - find elements of more than one css class - Stack Overflow
automated testing - How to select element by class when multiple elements match? - Software Quality Assurance & Testing Stack Exchange
Videos
To select the div with the class you can use css (preferred for readability)
BY.css
Example
driver.find_element(By.CSS, 'div.dept-time')
or xpath
BY.xpath
Example
driver.find_element(By.XPATH, '//div[@class=dept-time]
or if there are multiple classes for that element, use
contains
Example
//div[contains(@class, 'dept-time')]
If more than 1 div element with that class exist and you want the first one you can also use:
[1]
Example (XPATH)
//div[@class='dept-time'])[1]
Example (CSS)
div.dept-time:first
Using css selectors, instead of class, the syntax to select the tag with a specific class/attribute is tag[attribute='value']. So in your case:
[element.text for element in self.browser.find_elements(By.CSS_SELECTOR, "div[class='dept-time']")]
More information on css selectors: https://www.w3schools.com/cssref/css_selectors.asp