🌐
Reddit
reddit.com › r/learnpython › finding items with selenium by css selector using multiple attributes
r/learnpython on Reddit: finding items with selenium by CSS selector using multiple attributes
March 23, 2023 -

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)

🌐
TESTEROPS
seleniumwithjavapython.wordpress.com › selenium-with-python › web-elements-locating-mechanisms › handling-multiple-css-selectors
Handling Multiple CSS Selectors - testerops - WordPress.com
July 20, 2016 - """ element5=driver.find_element_by_css_selector("label[class^='class-name1']") print(element5.text) sleep(5) element6=driver.find_element_by_css_selector("label[class$='class-name2']") print(element6.text) sleep(5) element7=driver.find_element_by_css_selector("input[class*='class-name2']") element7.clear() element7.send_keys('narkanda@gmail.com') sleep(5) def tearDown(self): self.driver.quit() if __name__ == '__main__': unittest.main()
Discussions

html - How to loop multiple elements in python selenium (different CSS selectors) - Stack Overflow
I am trying to loop inside a class offer-list-wrapper which has multiple elements inside, almost all the elements are common in the web page for search A and search B (I am scraping a crawler). As... More on stackoverflow.com
🌐 stackoverflow.com
March 5, 2020
Pulling multiple elements from the same page
I would recommend not using XPath for a multitude of reasons and would use the same CSS selectors before and store in a List. Then use a for loop and use .get(i) and .get(I+1) to get the values, increment your loop by 2. More on reddit.com
🌐 r/selenium
32
1
September 18, 2022
python - find_element_by_class_name for multiple classes - Stack Overflow
Selenium in the API for Python / Django has the function driver.find_element/elements_by_class_name (), but it is not written whether it can be used for several classes I need choose element with s... More on stackoverflow.com
🌐 stackoverflow.com
Selenium with Python - find elements of more than one css class - Stack Overflow
I need to lookup a list of items that have various css classes, but have them returned in a single list, so I can loop through it, in below case I need to pick up all 4 items. More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
🌐
Python Examples
pythonexamples.org › python-selenium-find-element-by-css-selector
How to find Element by CSS Selector using Selenium Python
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By # Setup chrome driver driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) # Navigate to the url driver.get('/tmp/selenium/index-52.html') # Find element by CSS Selector my_div = driver.find_element(By.CSS_SELECTOR, 'div.xyz') print(my_div.get_attribute("outerHTML")) # Close the driver driver.quit() ... Now, let us consider the scenario where there are multiple HTML Elements with a match for the given CSS selector string 'div.xyz'.
🌐
ScrapeOps
scrapeops.io › home › selenium web scraping playbook › python selenium find elements css
Python Selenium Guide - Finding Elements by CSS Selectors | ScrapeOps
January 8, 2024 - Now that we have a basic understanding of CSS selectors, let's apply this new knowledge. The code example below finds all tag elements on the page. from selenium import webdriver from selenium.webdriver.common.by import By #open an instance of Chrome driver = webdriver.Chrome() #navigate to the page driver.get("https://quotes.toscrape.com") #look for custom elements named "tag" selector = ".tag" #find all elements with this selector elements = driver.find_elements(By.CSS_SELECTOR, selector) #print the text of each element for element in elements: print(element.text) #close the browser driver.quit()
🌐
Selenium Python
selenium-python.readthedocs.io › locating-elements.html
4. Locating Elements — Selenium Python Bindings 2 documentation
from selenium.webdriver.common.by import By driver.find_element(By.XPATH, '//button[text()="Some text"]') driver.find_elements(By.XPATH, '//button') The attributes available for the By class are used to locate elements on a page. These are the attributes available for By class: ID = "id" NAME = "name" XPATH = "xpath" LINK_TEXT = "link text" PARTIAL_LINK_TEXT = "partial link text" TAG_NAME = "tag name" CLASS_NAME = "class name" CSS_SELECTOR = "css selector"
🌐
Readthedocs
selenium-python-test.readthedocs.io › en › latest › locating-elements.html
4. Locating Elements — Selenium Python Bindings 2 documentation
from selenium.webdriver.common.by import By driver.find_element(By.XPATH, '//button[text()="Some text"]') driver.find_elements(By.XPATH, '//button') ... ID = "id" XPATH = "xpath" LINK_TEXT = "link text" PARTIAL_LINK_TEXT = "partial link text" NAME = "name" TAG_NAME = "tag name" CLASS_NAME = "class name" CSS_SELECTOR = "css selector"
🌐
DevQA
devqa.io › selenium-css-selectors
Selenium CSS Selectors Examples
In the above snippet, we want to select an available day (i.e. the two last div elements) As can be seen, all four divs contain “calendar-day-“ but the first two also contain “unavailable” which we don’t want. The CSS selector for Not selecting the first two divs is · driver.findElement(By.cssSelector("div[class*=calendar-day-]:not([class*='unavailable'])"));" ... There are occasions when there are multiple child elements within the same parent element such as list elements
Find elsewhere
🌐
YouTube
youtube.com › software testing mentor
Selenium CSS Selector #3 - CSS Selector with Multiple Attributes - YouTube
❖ FREE Training's at https://training.rcvacademy.com ❖ In this Selenium CSS selector tutorial we will learn how to write Selenium CSS selector using multiple...
Published   April 2, 2020
Views   549
🌐
GeeksforGeeks
geeksforgeeks.org › locating-multiple-elements-in-selenium-python
Locating multiple elements in Selenium Python - GeeksforGeeks
September 26, 2024 - To check practical Implementation, visit - find_elements_by_class_name() driver method – Selenium Python · Note: command find_elements_by_class_name() is deprecated · With this strategy, all elements with the matching CSS selector will be returned.
🌐
Reddit
reddit.com › r/selenium › pulling multiple elements from the same page
r/selenium on Reddit: Pulling multiple elements from the same page
September 18, 2022 -

So I am making a Garmin crawling script and I want it to pull multiple elements if they are from the same day and add the time together for some activities, time, distance and heart rate for another for example.

Layout of website

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import login as login
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import datetime
import time

x = datetime.datetime.now()
x = x.strftime("%b %d")

driver = browser = webdriver.Firefox()
driver.get("https://connect.garmin.com/modern/activities")

driver.implicitly_wait(1)

iframe = driver.find_element(By.ID, "gauth-widget-frame-gauth-widget")
driver.switch_to.frame(iframe)

driver.find_element("name", "username").send_keys(login.username)

driver.find_element("name", "password").send_keys(login.password)
driver.find_element("name", "password").send_keys(Keys.RETURN)

driver.switch_to.default_content()

time.sleep(10)

driver.find_element("name", "search").send_keys("Reading")
driver.find_element("name", "search").send_keys(Keys.RETURN)

time.sleep(2)

element = driver.find_element(By.CSS_SELECTOR, '.activity-date > span:nth-child(1)').text

time.sleep(2)
print(element)

time_read = 0

if element == x:
	spent = driver.find_element(By.CSS_SELECTOR, 'li.list-item:nth-child(1) > div:nth-child(2) > div:nth-child(5) > div:nth-child(2) > span:nth-child(1) > span:nth-child(1)').text

        result = time.strptime(spent, "%H:%M:%S")

	time_read += result.tm_hour * 60

	time_read += result.tm_min

	print(time_read)

So this is my current code. It finds the date, checks if it is today and adds the minutes to the variable time_read.

Now I need some help in how I go about adding multiple elements, and if this can be done with some kind of for loop, where it loops between the dates and can then extract the time from the element?

Do I need to set them up one by one, since I need to provide which element a specific iteration needs to pull from? So maybe I should have 5 or 6 checks for example, instead of some kind of loop that goes through and does it? Then it will be a lot of manual work, which makes me question if there isn't a better way to deal with it.

I do not want to use CSV.

Some relevant HTML

<div class="pull-left activity-date date-col">
        <span class="unit">Sep 14</span>
        <span class="label">2022</span>
    </div>

<span class="unit" title="3:32:00"><span class="" data-placement="top" title="3:32:00">3:32:00</span></span>

<span class="unit" title="1:00:00"><span class="" data-placement="top" title="1:00:00">1:00:00</span></span>
<span class="" data-placement="top" title="1:00:00">1:00:00</span>

Also a bit unsure what the best way is to locate elements? Is CSS.SELECTOR good or should I use XPATH preferably?

Thanks

🌐
TutorialsPoint
tutorialspoint.com › home › selenium › selenium webdriver: identify multiple elements
Selenium Webdriver - Identify Multiple Elements
April 7, 2021 - Also, the value entered within the edit box (obtained from the get_attribute method) - Selenium Python gets printed in the console. Once we navigate to a webpage, we have to interact with the webelements available on the page like clicking a link/button, entering text within an edit box, and so on to complete our automation test case. For this, our first job is to identify the elements. We can create a css selector for their identification and utilize the method find_elements_by_css_selector.
🌐
TOOLSQA
toolsqa.com › selenium-webdriver › css-selectors-in-selenium
How to use and create CSS Selectors in Selenium with examples?
Subsequently, we can use them together to create a CSS Selector for locating the web element, as shown below: textarea.form-control[placeholder='Current Address'] ... Then we provided the value of the class attribute. In the end, inside the square bracket, we provided the placeholder attribute and its value. So this way, we can combine various attributes of an HTML element to locate the web element in Selenium uniquely. With the ever-growing new technologies of web development, multiple times, the web pages are created dynamically.
🌐
Codeloop
codeloop.org › home › how to use css selectors in python selenium
How to Use CSS Selectors in Python Selenium - Codeloop
March 28, 2024 - A: Yes, you can use find_elements_by_css_selector() method to locate multiple elements. This method returns a list of all matching elements found on the page. Q: What types of CSS selectors are available in Python Selenium?
🌐
Stack Overflow
stackoverflow.com › questions › 33855026 › selenium-with-python-find-elements-of-more-than-one-css-class
Selenium with Python - find elements of more than one css class - Stack Overflow
May 24, 2017 - elements = driver.find_elements_by_css_selector(".dropdown") # or elements = driver.find_elements_by_class_name("dropdown") # elements[0] # elements[1] # ...
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2017 › 09 › 26 › how-to-locate-web-element-which-has-multiple-class-names
How To Locate Web Element Which Has Multiple Class Names
September 26, 2017 - driver.findElement(By.cssSelector(“.required_field.cityPadRight.ac_input.origin_ac”)).sendKeys(“DELHI”); package SpecialConcepts; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; import io.github.bonigarcia.wdm.WebDriverManager; public class ElementWithMultipleClassNames { @Test public void multipleClassnameWithClassNameLocator() { WebDriverManager.chromedriver().setup(); WebDriver driver=new ChromeDriver(); driver.get("https://www.yatra.com/"); driver.findElement(By.className("requi
🌐
GitHub
iqss.github.io › dss-webscrape › finding-web-elements.html
4 Finding Web Elements | Web Scraping Using Selenium Python
We then pass this XPath to the ... id on the path to the desired element. Otherwise, this method is not reliable. find_element_by_css_selector() and find_elements_by_css_selector() methods: Return element(s) that are found by the specified CSS selector....