我正在尝试创建一个词典列表,其中包含从网站上抓取的数据。 数据列表:价格,每克价格,品牌。
在第一部分中,我提取了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
请帮助找到解决方案。
答案 0 :(得分: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
的第二个循环“播放”。 (并且也要重置)。