【问题标题】:Python - previous list elements being overwritten by new elements during while loopPython - 在while循环期间,以前的列表元素被新元素覆盖
【发布时间】:2018-03-15 21:35:43
【问题描述】:

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

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

【问题讨论】:

  • urls 列表移出while 循环
  • 谢谢,严重的菜鸟错误

标签: python list while-loop scrape


【解决方案1】:
domain = "https://domain234dd.com"
count = 0

urls = []
while count < 10:

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

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

    print(count)
    count += 1

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 哈哈不,我也是初学者,昨天花了一个多小时感到困惑,因为我的 with 语句无法打开文件。我忘记在 ()'a 之前输入 open。大声笑它发生在每个人身上。 (我希望)
    【解决方案3】:

    因为您在循环的每次迭代中将urls 重置为一个空列表。你应该把它移到循环之前。

    (注意,整个事情最好用for循环来表示。)

    【讨论】:

      猜你喜欢
      • 2016-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 2019-09-05
      • 2017-10-28
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多