Search code examples
pythonseleniumxpathcss-selectorswebdriverwait

How to extract the Subtotal Price using Selenium and Python


I am using Xpath and having trouble pulling out information I need.

It is basically a Price - Subtotal. The HTML Image is attached, and the xpath code I am using is below. What am I missing? At the end I am looking to get the price value into a string.

w = driver.find_element_by_xpath('//*[@id="order-summary"]/section/section[3]/div/table/tbody/tr[2]/td/span')
print(w.text())

enter image description here


Solution

  • To print the Price - Subtotal text i.e. $27.99 you can use either of the following Locator Strategies:

    • Using css_selector and get_attribute("innerHTML"):

      print(driver.find_element(By.CSS_SELECTOR, "td.total-line__price > span.order-summary__emphasis").get_attribute("innerHTML"))
      
    • Using xpath and text attribute:

      print(driver.find_element(By.XPATH, "//td[@class='total-line__price']/span[contains(@class, 'order-summary__emphasis')]").text)
      

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

    • Using CSS_SELECTOR and text attribute:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "std.total-line__price > span.order-summary__emphasis"))).text)
      
    • Using XPATH and get_attribute("innerHTML"):

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//td[@class='total-line__price']/span[contains(@class, 'order-summary__emphasis')]"))).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

    You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


    References

    Link to useful documentation: