Home > front end >  Error using Selenium (Python): Unable to find class in HTML source code
Error using Selenium (Python): Unable to find class in HTML source code

Time:12-28

I'm learning how to use Selenium. I was doing some testing, but got this error:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: .layout layout-base

My Code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.get("https://page.onstove.com/epicseven/global/list/e7en003?listType=2&direction=latest&page=1")
driver.find_element(By.CLASS_NAME,"layout layout-base")

Image of: The source code I'm trying to find using find_element.

What am I doing wrong?

CodePudding user response:

layout layout-base are two class name values separated by a space.
To locate this element you can use any of the following ways:

driver.find_element(By.CLASS_NAME,"layout.layout-base")

Or

driver.find_element(By.CSS_SELECTOR,"div.layout.layout-base")

Or

driver.find_element(By.XPATH,"//div[@class='layout layout-base']")

CodePudding user response:

You can't pass multiple classnames as argument through find_element(By.CLASS_NAME,"classname") and doing so you will face an error as:

invalid selector: Compound class names not permitted

Solution

As an alternative you can use either of the following Locator Strategies:

  • Using CLASS_NAME layout:

    driver.find_element(By.CLASS_NAME, "layout")
    
  • Using CLASS_NAME layout:

    driver.find_element(By.CLASS_NAME, "layout-base")
    
  • Using CSS_SELECTOR:

    driver.find_element(By.CSS_SELECTOR, ".layout.layout-base")
    
  • Using XPATH:

    driver.find_element(By.XPATH, "//*[@class='layout layout-base']")
    
  • Related