Home > Net >  Same webElement is being looped in Selenium
Same webElement is being looped in Selenium

Time:12-17

I am trying to loop through webelements in Selenium but the same element is being looped in python.

My HTML code is

<div>
  <div >
     <span >One</span>
  </div>

<div >
     <span >Two</span>
  </div>

<div >
     <span >Three</span>
  </div>
</div>

The python code for looping through webelement

profiles = browser.find_elements(By.CLASS_NAME, 'profile')
for profile in profiles:
   print(profile.get_attribute('outerHTML'))
   print(profile.find_element(By.XPATH, '//span[@class, "name"].get_attribute('innerHTML'))
   print("Next item \n\n")

Output

<div >
     <span >One</span>
  </div>
One
Next item



<div >
     <span >Two</span>
  </div>
One
Next item



<div >
     <span >Three</span>
  </div>
One
Next item

As you can see that the div printed is unique so the loop is working, but when I try to find element inside that div, I am getting the result of first item itself (i.e "One").

I tried to make the a variable None at the begning and then assigning the profile variable into that assuiming there is some issue with the caching of variable but same result.

The output expected is


<div >
     <span >One</span>
  </div>
One
Next item



<div >
     <span >Two</span>
  </div>
Two
Next item



<div >
     <span >Three</span>
  </div>
Three
Next item

CodePudding user response:

You need to use relative XPath, like this:

profiles = browser.find_elements(By.CLASS_NAME, 'profile')
for profile in profiles:
   print(profile.get_attribute('outerHTML'))
   print(profile.find_element(By.XPATH, './/span[@class, "name"].get_attribute('innerHTML'))
   print("Next item \n\n")

All the difference is with a dot . making XPath to start searching inside the current node profile. Otherwise it searches from the top of the page.

  • Related