IndexError: список индексов вне диапазона. Попытка создать список словарей для элементов BeatifulSoup - PullRequest
1 голос
/ 03 апреля 2020

Я пытаюсь создать список словарей с данными, скопированными с веб-сайта. Список данных: цена, цена за грамм, марка.

В первой части, где я извлекаю 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/WEBSCRAPPING/Work with Soup data.py", line 41, in <module>
    list_of_sku[i]["Brand"] = str(row.text)
IndexError: list index out of range

Пожалуйста, помогите найти решение.

1 Ответ

1 голос
/ 03 апреля 2020

Различные уровни отступа между 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)

, в результате чего 2-й l oop «проигрывается» для каждого divs. (и сброс тоже).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...