Home > Enterprise >  Variable value don't get update in while loop with python - selenium
Variable value don't get update in while loop with python - selenium

Time:10-04

I am trying to load more elements and scroll as more elements as loaded(infinite scrolls where elements are loaded as your scroll)

Problem : jobCards value changes only once and then don't change even though the loops run again, Does not even change for once if assigned any value to it before while loop runs

def totalJobs(self,):
    jobCards = self.find_elements_by_css_selector(
        'div[class^="job-cardstyle__JobCardHeader"]')
    return jobCards

while True:
    time.sleep(10)
    jobCards = self.totalJobs()
    print("Total Jobs - "   str(len(jobCards)))
    self.execute_script(
        "arguments[0].scrollIntoView({behavior: 'smooth',block: 'center'});", jobCards[len(jobCards)-1])
    #Some break Condition based on len(jobCards)

CodePudding user response:

The variable jobCards is getting redefined every time. And you are just calling the function without adding previous length of the jobCards to it.

Try like below and confirm:

jobCards = [] # Make "jobCards" a class variable
def totalJobs(self,templist):
    templist = self.find_elements_by_css_selector('div[class^="job-cardstyle__JobCardHeader"]')
    return templist

while True:
    time.sleep(10)
    jobCards = jobCards   self.totalJobs(templist = []) # Keeping adding new length to previous one.
    print("Total Jobs - "   str(len(jobCards)))
    driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth',block: 'center'});", jobCards[len(jobCards)-1])
    #Some break Condition based on len(jobCards)

CodePudding user response:

I think you're code looks fine, variable jobCards also gets update each time.

totaljobs() retuns list of elements which has always similar length.

for example when you scroll first time, same number elements loads on page. so always number of elements (len) are same.

Can you please try to print elements instead of length of elements.

  • Related