2

Может кто подсказать как исправить?

Cursor.execute(_SQL, (pricelist['name']))
TypeError: list indices must be integers or slices, not str

def BB_parse(base_url, headers):
    pricelist = []
    session = requests.Session()
    request = session.get(base_url, headers = headers)
    if request.status_code == 200:
        soup = bs(request.content, 'lxml')
        container_main = soup.find_all('div', {'class': 'content-wrapper'})
        for c1 in container_main:
            try:
                article = c1.find('div', {'class': 'article'}).text.strip().replace("Артикул: ", "")
                name = c1.select('h1')[0].text
                description = c1.find('div', {'class': 'description'}).text.strip()
                available = c1.find('div', {'class': 'avl'}).text.strip()
                price = c1.find('span', {'class': 'catalog-detail-item-price' }).text.replace("Цена:", "").replace("тг.", "").replace("за шт", "").strip()
                oldprice = c1.find('span', {'class': 'catalog-detail-item-price-old' }).text.replace("Цена:", "").replace("тг.", "").replace("за шт", "").replace(" ", "").strip()
                Category1 = c1.find_all('span', {'itemprop': 'title'})[1].text
                Category2 = c1.find_all('span', {'itemprop': 'title'})[2].text
                Category3 = c1.find_all('span', {'itemprop': 'title'})[3].text
                catalog_detail_pictures = c1.find_all('div', {'class': 'catalog-detail-pictures'})
                image1 = c1.find_all('a', {'rel': 'lightbox'})[0]['href']
                image2 = c1.find_all('a', {'rel': 'lightbox'})[1]['href']
                image3 = c1.find_all('a', {'rel': 'lightbox'})[2]['href']
            except:
                pass


            for count, tag in enumerate(soup.find_all(class_='name')):
                try:
                    if tag.text == 'ISBN':
                       code = soup.find_all(class_='val')[count].text
                    if tag.text == 'Издательство':
                       Publish = soup.find_all(class_='val')[count].text
                    if tag.text == 'Авторы':
                       Authors = soup.find_all(class_='val')[count].text
                    if tag.text == 'Серия':
                       Series = soup.find_all(class_='val')[count].text
                    if tag.text == 'Переплет':
                       Blinding = soup.find_all(class_='val')[count].text
                    if tag.text == 'Количество страниц':
                       Count_Page = soup.find_all(class_='val')[count].text
                    if tag.text == 'Ширина':
                       Width = soup.find_all(class_='val')[count].text
                    if tag.text == 'Высота':
                       Height = soup.find_all(class_='val')[count].text
                    if tag.text == 'Дата последнего тиража':
                       Date = soup.find_all(class_='val')[count].text


                except:
                  pass

            pricelist.append({
                     'name': name,
                     'article': article,
                     'price': price,
                     'oldprice': oldprice,
                     'available': available,
                     'code': code,
                     'Publish': Publish,
                     'Authors': Authors,
                     'Series': Series,
                     'Blinding': Blinding,
                     'Count_Page': Count_Page,
                     'Width': Width,
                     'Height': Height,
                     'Date': Date,
                     'Category1': Category1,
                     'Category2': Category2,
                     'Category3': Category3,
                     'image1': image1,
                     'image2': image2,
                     'image3': image3
                })

        write_sql(pricelist)
        print(len(pricelist))



    else:
        print('ERROR or Done. Status_code = ' + str(request.status_code))

    return pricelist

def write_sql(pricelist):
    DB = {'host': '',
         'user': '',
         'password': '',
         'database': ''}


    conn = mysql.connector.connect(**DB)
    Cursor = conn.cursor()

    _SQL = "INSERT INTO products (Наименование, Артикул, Цена, Старая_цена, Наличие, Код, Издательство, Авторы, Серия, Переплет, Количество_страниц, Ширина, Высота, Дата_тиража, Родительская_категория, Категория, Подкатегория, Картикнка_1 Картикнка_2, Картикнка_3) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    Cursor.execute(_SQL, (pricelist['name'],
        pricelist['article'],
        pricelist['price'],
        pricelist['oldprice'],
        pricelist['available'],
        pricelist['code'],
        pricelist['Publish'],
        pricelist['Authors'],
        pricelist['Series'],
        pricelist['Blinding'],
        pricelist['Count_Page'],
        pricelist['Width'],
        pricelist['Height'],
        pricelist['Date'],
        pricelist['Category1'],
        pricelist['Category2'],
        pricelist['Category3'],
        pricelist['image1'],
        pricelist['image2'],
        pricelist['image3'],
        ))
    DB.commit()
    Cursor.close()
    DB.close()


BB_parse(base_url, headers)
0

1 ответ 1

4

Переменная pricelist является списком. Оператор индексирования [] для объекта типа list принимает только целые числа (индексы элементов списка) или объект типа slice в качестве аргумента. 'name' - не является ни целым числом ни slice'ом.

Поэтому команда:

pricelist['name']

вызывает ошибку:

TypeError: list indices must be integers or slices, not str


Если я правильно понимаю ваш код, переменная pricelist - список записей-словарей, которые вы хотите вставить в SQL таблицу.

Сделать это можно так:

records = [tuple(x.values()) for x in pricelist]
Cursor.executemany(_SQL, records)
6
  • Спасибо! изменил _SQL заработал. По records не хочет пускать выдает ошибку "mysql.connector.errors.ProgrammingError: Failed processing format-parameters; 'builtin_function_or_method' object is not iterable"
    – w2God
    19 янв 2020 в 17:53
  • @w2God, а первый вариант работает? 19 янв 2020 в 18:00
  • Работает по вашему примеру, вписав переменные в VALUES. первый вариант не сработал -mysql.connector.errors.ProgrammingError: Failed processing format-parameters; 'builtin_function_or_method' object is not iterable, в чем может быть проблема? Может кому то будет полезно.
    – w2God
    19 янв 2020 в 18:03
  • @w2God, исправил ответ - попробуйте сейчас пожалуйста... 19 янв 2020 в 18:15
  • 2
    Проверил, заработало! Благодарю.
    – w2God
    19 янв 2020 в 18:27

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.