【问题标题】:IndexError: list index out of range. Trying to create a list of dictionaries for BeatifulSoup itemsIndexError:列表索引超出范围。尝试为 BeautifulSoup 项目创建字典列表
【发布时间】:2020-07-16 02:02:45
【问题描述】:

我正在尝试使用从网站上抓取的数据创建一个字典列表。 数据列表:价格、每克价格、品牌。

在第一部分,我提取 price 和 price_per_gramm 并将数据附加到列表中,一切正常。 现在我有一个字典列表,其中只有一个字段“品牌”为空。 所以我尝试用实际数据替换那些空字段并遇到IndexError。

soup = BeautifulSoup(open("./FULL_data.html"), "html.parser")
list_of_sku = []

for divs in soup.find_all('div', attrs={"class" : "col-xs-6 col-sm-4"}):
    item = {"Brand": "",
            "price": "",
            "price per gramm": ""}
    links = divs.find_all("tr")
    for row in links:
        # We get list of prices here
        item_text = row.find('td')
        item_text2 = row.find('span', {"class": "text-primary"}).text
        if item_text and item_text2:
            item["price"] = str(item_text.text)
            item["price per gramm"] = str(item_text2)
            list_of_sku.append(item)

    #We get a brand here
    i=0
    for row in soup.find_all('div', attrs={"class" : "js-equalized-brand"}):
        list_of_sku[i]["Brand"] = str(row.text)
        print(list_of_sku[i]["Brand"])
        i += 1
    print(list_of_sku)

这是一个错误:

    Original Stash

Traceback (most recent call last):
  File "/Users/PycharmProjects/MyFirstOne/WEBSCRAPING/Work with Soup data.py", line 41, in <module>
    list_of_sku[i]["Brand"] = str(row.text)
IndexError: list index out of range

请帮忙寻找解决办法。

【问题讨论】:

  • i=0 之后添加print(list_of_sku) 并将输出添加到您的问题(如果仍需要答案)
  • 在第二个注释中,检查i=0 的标识和下面的代码;不应该和for divs in soup.find_all('div', attrs={"class" : "col-xs-6 col-sm-4"})处于同一水平?
  • 我添加了它,只显示了一行。所以我在“i = 0”之前加倍了一个“divs”循环,现在一切正常。谢谢!!!!
  • 不客气!将建议添加到带有详细解释的答案中。

标签: python-3.x list dictionary beautifulsoup index-error


【解决方案1】:

for divs in soup.find_all('div', attrs={"class" : "col-xs-6 col-sm-4"}): 之间的不同缩进级别

i=0
for row in soup.find_all('div', attrs={"class" : "js-equalized-brand"}):
    list_of_sku[i]["Brand"] = str(row.text)
    print(list_of_sku[i]["Brand"])
    i += 1
print(list_of_sku)

因此导致每个divs 的第二个循环“播放”。 (以及重置)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    相关资源
    最近更新 更多