Search code examples
pythonloopsinstagramscreen-scraping

(SOLVED) How to make looping easier, then just changing the loop number in Python


How to make looping arguments[0].scrollTop more simple? let say if i want to make it looping 20x then i just change the looping number..

for i in range(1, loops_count + 1):
    browser.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)
    time.sleep(random.randrange(6, 10))
    browser.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)
    time.sleep(random.randrange(6, 10))
    browser.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)
    time.sleep(random.randrange(6, 10))
    browser.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)
    time.sleep(random.randrange(6, 10))
    

    all_div = followers_ul.find_elements_by_tag_name("li")
    for us in all_div:
        us = us.find_element_by_tag_name("a").get_attribute("href")
        if result == 'usernames':
            us1 = us.replace("https://www.instagram.com/", "")
            us = us1.replace("/", "")
        followers_list.append(us)
    time.sleep(4)
    f3 = open('userlist.txt', 'w')
    for list in followers_list:
        f3.write(list + '\n')
    print(f'Got: {len(followers_list)} usernames of {amount}. Saved to file.')
time.sleep(random.randrange(5, 7))

I add nested loop

for i in range(1, loops_count + 1):
    for j in range(1,31):
        browser.execute_script(f"arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)

Solution

  • I don't know if it's what you're searching, you can do :

    for i in range(1, loops_count + 1):
        browser.execute_script(f"arguments[{i}].scrollTop = arguments[{i}].scrollHeight", followers_ul)
                        
    

    Adding f"{variable}" to a string is a simple way to have a string with variable. In this case, it will replace in the string the i the loop count. If it's not that, could you precise your question ?