首页 > 解决方案 > 爬取数据和调整数据时列表索引超出范围

问题描述

我正在尝试从 url (1st loop) 列表中抓取数据。在每个 url(第二个循环)中,我想通过添加更多数据来调整 product_reviews['reviews'] (列表)。这是我的代码:

import requests
import pandas as pd

df = pd.read_excel(r'C:\ids.xlsx')
ids = df['ids'].values.tolist() 
link = 'https://www.real.de/product/%s/'
url_test = 'https://www.real.de/pdp-test/api/v1/%s/product-attributes/?offset=0&limit=500'
url_test1 = 'https://www.real.de/pdp-test/api/v1/%s/product-reviews/?offset=0&limit=500'


for i in ids:
    
    product_id = requests.get(url_test %i).json()
    product_reviews = requests.get(url_test1 %i).json()
    
    for x in range(0,len(product_reviews['reviews']),1):
        product_reviews['reviews'][x]['variantAttributes'].append(str(int(100*float(product_reviews['reviews'][x]['variantAttributes'][1]['label'].replace(" m","").replace(",",".")))))
        product_reviews['reviews'][x]['variantAttributes'].append(str(int(100*float(product_reviews['reviews'][x]['variantAttributes'][0]['label'].replace(" m","").replace(",","."))))) 
        product_reviews['reviews'][x]['size']= str(int(100*float(product_reviews['reviews'][x]['variantAttributes'][1]['label'].replace(" m","").replace(",","."))))+ 'x' + str(int(100*float(product_reviews['reviews'][x]['variantAttributes'][0]['label'].replace(" m","").replace(",","."))))
        product_reviews['reviews'][x]['url'] = link %i
        product_reviews['reviews'][x]['ean'] = product_id['defaultAttributes'][0]['values'][0]['text']
        product_reviews['reviews'][x]['TotalReviewperParent'] =  product_reviews['totalReviews']
    
    df = pd.DataFrame(product_reviews['reviews'])
    df.to_excel( r'C:\new\str(i).xlsx', index=False)

但是,当我运行此代码时,它会返回错误:

第 24 行,在 product_reviews['reviews'][x]['variantAttributes'].append(str(int(100*float(product_reviews['reviews'][x]['variantAttributes'][1]['label' ].replace("m","").replace(",",".")))))

IndexError:列表索引超出范围

当我为 1 个 url 运行第二个循环时,它运行良好,但是当我将第二个循环放在第一个循环内时,它返回错误。它的解决方案是什么?我的代码看起来很猴子。您知道如何改进我的代码以使其更短吗?

标签: pythonpandasweb-scrapingrequestweb-crawler

解决方案


请在未来尝试创建一个最小的、可重现的示例。我们无权访问您的“ids.xlsx”,因此我们无法验证问题是与您列表中的特定 ID 相关还是一般问题。

取一个随机 id, 338661983, 并使用以下代码:

import requests

link = 'https://www.real.de/product/%s/'
url_attributes = 'https://www.real.de/pdp-test/api/v1/%s/product-attributes/?offset=0&limit=500'
url_reviews = 'https://www.real.de/pdp-test/api/v1/%s/product-reviews/?offset=0&limit=500'

ids = [338661983]

for i in ids:
    
    product_id = requests.get(url_attributes % i).json()
    product_reviews = requests.get(url_reviews % i).json()

    for review in product_reviews['reviews']:
      print(review)
      break

我得到以下输出:

{'reviewId': 1119427, 'title': 'Klasse!', 'date': '11.11.2020', 'rating': 5, 'isVerifiedPurchase': True, 'text': 'Originale Switch, schnelle Lieferung. Alles Top ', 'variantAttributes': [], 'author': 'hm-1511917085', 'datePublished': '2020-11-11T20:09:41+01:00'}

请注意,这variantAttributes是一个空列表。您收到 IndexError 是因为您尝试在该空列表的位置 1 处获取元素:

review['variantAttributes'][1]['label'].replace(" m","").replace(",",".")

推荐阅读