Python - 在 while 循环期间,先前的列表元素被新元素覆盖 [英] Python - previous list elements being overwritten by new elements during while loop

查看:27
本文介绍了Python - 在 while 循环期间,先前的列表元素被新元素覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我是 Python 新手,我想弄清楚为什么每次在 while 循环期间加载和抓取新页面时,我的列表都会覆盖以前的元素.先感谢您.

Hello I am new to Python and am trying to figure out why my list overwrites the previous elements every time a new page is loaded and scraped during the while loop. Thank you in advance.

def scrapeurls():
    domain = "https://domain234dd.com"
    count = 0

    while count < 10:

        page = requests.get("{}{}".format(domain, count))
        soup = BeautifulSoup(page.content, 'html.parser')
        data = soup.findAll('div', attrs={'class': 'video'})

        urls = []

        for div in data:
            links = div.findAll('a')
            for a in links:
                urls.append(a['href'])
                print(a['href'])

        print(count)
        count += 1

推荐答案

需要在循环前初始化 URL 列表.如果您在循环内部初始化,它每次都会将其设置为空.

You need to initialize the URL list before the loop. If you initialize inside the loop it sets it back to nothing every time.

这篇关于Python - 在 while 循环期间,先前的列表元素被新元素覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆