【问题标题】:IndexError while iterating迭代时出现索引错误
【发布时间】:2021-06-14 05:27:16
【问题描述】:

我在迭代时遇到了IndexError 的问题。该程序运行良好,直到一切都完成,没有更多的“子网站”可以访问,然后它崩溃了,因此无法保存在 .txt 中。

回溯(最近一次通话最后一次)

newUrl = nextpage[counter]['href']
IndexError: list index out of range

代码

from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
import json
class Olx():

    def __init__(self, url):
        self.url = url

    def getPrice(self):
        """Get prices from olx"""
        html = urlopen(self.url)
        bs = BeautifulSoup(html, 'html.parser')
        price = bs.findAll('p', class_='price')
        return price

    def nextPage(self):
        """Go to the next page"""
        html = urlopen(self.url)
        bs = BeautifulSoup(html, 'html.parser')
        pageButton = bs.findAll('a', {'class': 'block br3 brc8 large tdnone lheight24'})
        try:
            return pageButton
        except AttributeError:
            None
        else:
            return pageButton

    

olxprices = Olx('https://www.olx.pl/nieruchomosci/mieszkania/wynajem/olsztyn/').getPrice()
nextpage = Olx('https://www.olx.pl/nieruchomosci/mieszkania/wynajem/olsztyn/').nextPage()
counter = 0

output = []
while len(nextpage) > 0:
    for price in olxprices:
        output.append(price.get_text().strip())
        print(price.get_text().strip())
    newUrl = nextpage[counter]['href']
    olxprices = Olx(newUrl).getPrice()
    counter += 1

print(output)

【问题讨论】:

    标签: python loops beautifulsoup iteration index-error


    【解决方案1】:

    您可以尝试使用异常。

    while len(nextpage) > 0:
        try:
            for price in olxprices:
                output.append(price.get_text().strip())
                print(price.get_text().strip())
            newUrl = nextpage[counter]['href']
            olxprices = Olx(newUrl).getPrice()
            counter += 1
        except IndexError:
            break    
    

    (或在那里做任何你想做的例外) 如果这不能回答你的问题,可能是因为页面的长度保持不变,所以你可能也想遍历它。

    【讨论】:

      【解决方案2】:

      len(nextpage) 永远不会改变,所以 while 循环永远不会结束,最终counter 索引超过了nextpage 的末尾。相反,请执行以下操作:

      for page in nextpage:
          for price in olxprices:
              output.append(price.get_text().strip())
              print(price.get_text().strip())
          newUrl = page['href']
          olxprices = Olx(newUrl).getPrice()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-30
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        相关资源
        最近更新 更多