Massimo Daul
Massimo Daul

Reputation: 74

WebDriver finding by class name

I am trying to find information on a webpage using the class attribute and selenium WeDriver. I am looking to print out the 6 + 8 in the following HTML:

<a href="/#/basic-math-pre-algebra/16869" class="question-link"><b>6 + 8</b> = </a>

I am searching by class name, and I have tried XPATH as well. The XPATH is:

//*[@id="question-link"]

My code:

from selenium import webdriver

url_rice = 'http://freerice.com/#/basic-math-pre-algebra/16869'

driver = webdriver.Chrome()
driver.get('http://freerice.com/#/basic-math-pre-algebra/16869')

def question():
    print(driver.find_elements_by_class_name("question-link"))

question()

driver.quit()

Upvotes: 0

Views: 433

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

As per your question you must not restrict your tests to class attribute only. At times CSS-SELECTOR are found to be better performing where as at times XPATH comes handy.

As per the HTML DOM the text 6 + 8 is within the ancestor node having the class attribute as question-link which have a descendent node as <b> which actually contains the desired text. So using either a CSS-SELECTOR or a XPATH you need to identify the <b> node.

To extract the information, you need to induce WebDriverWait for the desired element to be visible and you can use the following solution:

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

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('http://freerice.com/#/basic-math-pre-algebra/16869')
print(WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.block-means-vocab div#question-title b"))).text)

Note: As per best practices always open the browser in maximized mode and disabling the infobars and extensions

Upvotes: 2

Related Questions