pythonselenium-webdriverxpathcss-selectorsfindelement

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


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()

Solution

  • 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: