1
votes

I have the following code: tag a with class "keep-product-list-cache" and tag div with class "promotion-tag grey" are under tag div with class = "product-wrapping".

I want to get the data-code (1017534) in class "image" under tag a from relative position of span class="content tc" under tag div with class "promotion-tag grey".

<div class="product-wrapping">
    <a class="keep-product-list-cache" href="/product/peach-gum-black-sugar-longan-tea-1017534-c2843">
        <div class="image">
            <img src="https://tore.com/images/tore/production/product/160px/1017534_1.jpg?1511440192" data-code="1017534" alt="tea">
                    </div>
    </a>
    <div class="promotion-tag grey">
        <span class="edge"></span>
        <span class="content tc">Sold Out</span>
        <span class="triangle"></span>
    </div>

I have tried the following to locate by parent / sibling position but it doesn't work:

id = driver.find_elements_by_xpath('div[@class="promotion-tag grey"]//span[@class="content tc"]/..//preceding-sibling::a//div[@class="image"]//img')

To get the attribute: id[i].get_attribute("data-code")

But the length of the returned list "id" is 0. Any idea? Thanks in advance!

2

2 Answers

1
votes

Oh. The only one mistake is that you forgot // at the beginning of the expression.

id = driver.find_elements_by_xpath('//div[@class="promotion-tag grey"]//span[@class="content tc"]/..//preceding-sibling::a//div[@class="image"]//img')
0
votes

As per the HTML to get the data-code (1017534) in class image under the <a> tag from relative position of span class="content tc" under tag div with class promotion-tag grey you can use the following line of code :

print(driver.find_element_by_xpath("//div[@class='promotion-tag grey']//span[@class='content tc']//preceding::a[@class='keep-product-list-cache']/div[@class='image']/img[contains(@src,'https://tore.com/images/tore/production/product')]").get_attribute("data-code"))