8

I have this HTML:

<div class="container">
    <div class="name">James</div>
    <div>Rodriguez</div>
    <div class="image">
        <div><img src="https://example.com/1.jpg"></div>
    </div>
</div>
<div class="container">
    <div class="name">Harry</div>
    <div>Kane</div>
    <div class="image">
        <div><img src="https://example.com/2.jpg"></div>
    </div>
</div>

How do I loop through all containers and get name, surname (second div) and image URL (img src)? So far I came up with this:

items = []

containers = driver.find_elements_by_xpath('//div[@class="container"]')

for items in containers:
    name = items.find_element_by_xpath('//div[@class="name"]')
    print(name.text)

This should give two names. However, I'm getting 'James' twice as output, and no 'Harry'.

Thanks!

2
  • So what is your exact question here? Commented Feb 11, 2018 at 19:20
  • It's there: how do I loop through all containers and get name, surname (second div) and image URL (img src)? Commented Feb 11, 2018 at 19:29

2 Answers 2

9

Try below solution to get required values

for item in containers:
    name = item.find_element_by_xpath('.//div[@class="name"]')
    surname = name.find_element_by_xpath('./following-sibling::div')
    image = surname.find_element_by_xpath('./following::img')
    print(name.text, surname.text, image.get_attribute('src'))
Sign up to request clarification or add additional context in comments.

1 Comment

hi can you explain more? I dont know why use ./following-sibling::div and './following::img'
8

When using // you are starting the search from the root node (<html>). Use . before the xpath to start the search from the element location

for items in containers:
    name = items.find_element_by_xpath('.//div[@class="name"]')
    print(name.text)

1 Comment

Thanks, it indeed was the case. I chose Andersson's anwer as it was a bit more elaborate in terms of finding other items.

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.