Search code examples
pythonseleniumselenium-webdriverwebdriverwaitgetattribute

Selenium Webdriver: How do I grab by class name?


GOAL: Print "Eden Ivy" onto my console.

I am following the documentation for Selenium Webdriver.

The following is the line of interest. Here is the screenshot:

screenshot.

HTML:

<a href="/model/77291/eden-ivy" title="Eden Ivy" class="sc-1b6bgon-7 cGUerq">Eden Ivy</a>

How exactly do I grab and print "Eden Ivy" ?

I tried:

name = driver.find_element_by_class_name('sc-1b6bgon')
print(name)

and

name = driver.find_element_by_class_name('sc-1b6bgon-7 cGUerq')
print(name)

But they don't seem to be working. What am I doing wrong?

Edit: I can't use the words "Eden Ivy" when grabbing, it has to be by element. So that I can use this function for other names.


Solution

  • It would be difficult to extract the innerHTML using the class attributes as they are dynamic in nature.

    To print the innerText Eden Ivy attribute you can use either of the following Locator Strategies:

    • Using xpath and text attribute:

      print(driver.find_element_by_xpath("//h2[text()]//following::div[1]/span/a").text)
      

    Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

    • Using XPATH and get_attribute("innerHTML"):

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h2[text()]//following::div[1]/span/a"))).get_attribute("innerHTML"))
      
    • Note : You have to add the following imports :

      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC