Search code examples
pythonseleniumselenium-webdrivercss-selectorswebdriverwait

Can't find element by name using selenium


I'm using selenium 4.7.2 and can't find the element by its name. The following code returns NoSuchElementException error:

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Get the website using the Chrome webbdriver
browser = webdriver.Chrome()
browser.get('https://www.woofshack.com/en/cloud-chaser-waterproof-softshell-dog-jacket-ruffwear-rw-5102.html')

# Print out the result
price = browser.find_element(By.NAME, 'data-price-665')
print("Price: " + price.text)

# Close the browser
time.sleep(3)
browser.close()

What's wrong in using find_element method?


Solution

  • Looks like you are using a wrong locator here. I see no element with name attribute value 'data-price-665' on that page.
    The following code is working:

    from selenium import webdriver
    from selenium.webdriver import ActionChains
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    options = Options()
    options.add_argument("start-maximized")
    
    webdriver_service = Service('C:\webdrivers\chromedriver.exe')
    driver = webdriver.Chrome(service=webdriver_service, options=options)
    
    wait = WebDriverWait(driver, 20)
    actions = ActionChains(driver)
    
    url = "https://www.woofshack.com/en/cloud-chaser-waterproof-softshell-dog-jacket-ruffwear-rw-5102.html"
    driver.get(url)
    
    price = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#product-price-665 .price")))
    print("Price: " + price.text)
    

    The output is:

    Price: €112.95