Selenium Python: Find Next Element and/or Find Changing Element

70 views Asked by At

Trying to find the price element of an item and return and store that attribute. The item name is clearly defined but the price varies.

Element HTML:

<div tabindex="0" class="item-img" style="background-image:url(&quot;//images.neopets.com/items/snowfood_chiapopblueberry.gif&quot;);" alt="Mmmm, a frozen blueberry Chia Pop.  Just what your Neopet needs to cool down." title="Mmmm, a frozen blueberry Chia Pop.  Just what your Neopet needs to cool down." border="1" onclick="confirmPurchase(this)" onkeyup="clickElement(event)" data-name="Blueberry Chia Pop" data-price="560" data-link="haggle.phtml?obj_info_id=8590&amp;stock_id=402513825&amp;g=3"></div>

Code I have tried:

time.sleep(10)
driver.get("https://www.neopets.com/objects.phtml?type=shop&obj_type=37")
time.sleep(5)
driver.find_element(By.XPATH, "//*[contains(text(), 'Blueberry Chia Pop')]")
print("Item In Stock")
item = driver.find_element(By.XPATH, "//div[@data-name='Blueberry Chia Pop']")
item_price = item.find_element(By.XPATH, "following-sibling::td").get_attribute()
1

There are 1 answers

0
undetected Selenium On BEST ANSWER

Given the HTML:

<div tabindex="0" class="item-img" style="background-image:url(&quot;//images.neopets.com/items/snowfood_chiapopblueberry.gif&quot;);" alt="Mmmm, a frozen blueberry Chia Pop.  Just what your Neopet needs to cool down." title="Mmmm, a frozen blueberry Chia Pop.  Just what your Neopet needs to cool down." border="1" onclick="confirmPurchase(this)" onkeyup="clickElement(event)" data-name="Blueberry Chia Pop" data-price="560" data-link="haggle.phtml?obj_info_id=8590&amp;stock_id=402513825&amp;g=3"></div>   

Assuming the item name being "Blueberry Chia Pop" and the item price being "560" to print the price you can use either of the following locator strategies:

  • Using css_selector:

    print(driver.find_element(By.CSS_SELECTOR, "div[data-name='Blueberry Chia Pop']").get_attribute("data-price"))
    
  • Using xpath:

    print(driver.find_element(By.XPATH, "//div[@data-name='Blueberry Chia Pop']").get_attribute("data-price"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.common.by import By