1

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 Answers 2

2

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')
Sign up to request clarification or add additional context in comments.

Comments

1

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

5 Comments

img node can not have any child nodes, so get_attribute("innerHTML") applied to img will always return None
@Andersson Thanks for pointing out. That's my bad, corrected now.
@DebanjanB I'm still getting None in this solution. I got the correct output from Buaban's reply though. Thanks for your help.
The methods called are different in the answers - maybe this is the difference ;-? Adding an s might go a long way
@Dilettant Thanks. As per the question I don't see any requirement of using find_elements because OP needs a definite value i.e. 1017534 where as if a proper Locator Strategy can be identified find_element will work smooth.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.