Home > Mobile >  selenium python for loop printing only first element repeatedly
selenium python for loop printing only first element repeatedly

Time:05-05

I am trying to get business info from this page.

Here I am selecting the main container for each item then using for loop for getting business title from each container.

Here is my code:

container = driver.find_elements_by_css_selector(".businessCapsule--mainRow")
for i in container:
    business_title = driver.find_element_by_css_selector('.text-h2')
    print(business_title) 

result:

Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd
Mirror & Glass Processing Ltd

Why It's printing only first item repeatedly? Where I am doing mistake in my above code.

If I tried without selecting main container then it's working.

business_title = driver.find_elements_by_css_selector(".text-h2")
for i in business_title:
        business_title = i.text
        print(business_title)

result:

Mirror & Glass Processing Ltd
J.E.D Double Glazing Repairs
B & R Glazing Co.Ltd
Durham Window & Door Centre Ltd
Ken Rose Joinery & Glazing

CodePudding user response:

Under the for loop code block you have to use i instead of driver

business_title = i.find_element_by_css_selector('.text-h2')
  • Related