Search code examples
pythonpython-3.xselenium-webdriverselenium-chromedriver

How to select element by css selector


Hey im trying to make typingtest bot but im getting error while selecting element by css selector.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

options = Options()
options.add_experimental_option("detach", True)

driver = webdriver. Chrome (service=Service(ChromeDriverManager().install()),
                        options=options)


words= []


url = "https://typetest.io/"
driver.get(url)

time.sleep(3)


class_name = "fc-button-label"
element = driver.find_element(By.CLASS_NAME, class_name) 
element.click()

input_field = driver.find_element(By.ID, "test-input")

words_elements = driver.find_element(By.CSS_SELECTOR, 'span[test-word]')

Im gettting error I dont know why


Solution

  • You're getting error, because you used incorrect selector.

    Word selector in you case is:

    words_elements = driver.find_elements(By.CSS_SELECTOR, 'span.test-word')
    

    You don't have attribute test-word, like you mentioned, you have class .test-word instead.