Locate text inside a html tag with selenium

Viewed 79

I want to get the price(234,40 €) from the below HTML with selenium.

<a class="js-sku-link sku-link" title="Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm Αδιάβροχο με Παλμογράφο (Black)" data-e2e-testid="sku-price-link" href="/s/30445632/Samsung-Galaxy-Watch4-Classic-Bluetooth-Stainless-Steel-46mm-%CE%91%CE%B4%CE%B9%CE%AC%CE%B2%CF%81%CE%BF%CF%87%CE%BF-%CE%BC%CE%B5-%CE%A0%CE%B1%CE%BB%CE%BC%CE%BF%CE%B3%CF%81%CE%AC%CF%86%CE%BF-Black.html"><span>από</span>234,39 €</a>

I have tried:

min_price = driver.find_element(By.CLASS_NAME, 'js-sku-link').get_attribute('text')


min_price = driver.find_element(By.XPATH, '//span[contains(text(), "από")]').get_attribute('innerHTML')
1 Answers

Please try this:

min_price = driver.find_element(By.XPATH, "//a[@title='Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm Αδιάβροχο με Παλμογράφο (Black)']").text

Or

min_price = driver.find_element(By.XPATH, "//a[contains(@title,'Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm')]").text

In case you need to add a wait to make element be visible you may use something like this:

min_price = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@title='Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm Αδιάβροχο με Παλμογράφο (Black)']"))).text

Or

min_price = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[contain(@title,'Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm)]"))).text

respectively
UPD
The //a[@title='Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm Αδιάβροχο με Παλμογράφο (Black)'] locator matches 3 elements inside the same product block. To access the price element you need to precise your locator.
This will give you the price of the product you are looking for: min_price = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@title='Samsung Galaxy Watch4 Classic Bluetooth Stainless Steel 46mm Αδιάβροχο με Παλμογράφο (Black)' and @data-e2e-testid='sku-price-link']"))).text
To get all the products on that page prices you can use something like this:

wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@data-e2e-testid='sku-price-link']")))
time.sleep(0.5)
prices = driver.find_element(By.XPATH, "//a[@data-e2e-testid='sku-price-link']")
for price in prices:
    print(price.text)
Related