首页 > 解决方案 > 网页抓取列表索引超出范围

问题描述

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = "https://www.amazon.in/s/ref=sr_nr_p_36_4?fst=as%3Aoff&rh=n%3A976419031%2Cn%3A1389401031%2Cn%3A1389432031%2Ck%3Amobile%2Cp_36%3A1318507031&keywords=mobile&ie=UTF8&qid=1543902909&rnid=1318502031"
uClient = uReq(my_url)
raw_html= uClient.read()
uClient.close()

page_soup = soup(raw_html, "html.parser")
containers = page_soup.findAll("div",{"class":"s-item-container"})

filename = "Product.csv"
f = open (filename , "w")

headers = "Name,Price,Prime \n"
f.write(headers)

for container in containers:

    title_container = container.findAll("div",{"class":"a-row a-spacing-mini"})
    product_name = title_container[0].div.a.h2.text

    price = container.findAll("span",{"class":"a-size-small a-color-secondary a-text-strike"})
    product_price = price[0].text.strip()

    prime = container.findAll("i",{"class":"a-icon a-icon-prime a-icon-small s-align-text-bottom"})
    product_prime = prime[0].text

    print("product_name : " + product_name)
    print("product_price : " + product_price)
    print("product_prime : " + product_prime)

    f.write(product_name + "," + product_price + "," + product_prime + "\n") 
f.close

我编写了我的第一个网络抓取代码,但由于某种原因它只循环了 4 次并显示错误消息(文件“firstwebscrapping.py”,第 23 行,在 product_price = price[0].text.strip() IndexError: list索引超出范围)。请,有人可以解释我在哪里做错了吗?

标签: pythonweb-scraping

解决方案


不是每个container人都有<span class="a-size-small a-color-secondary a-text-strike">

因此,当您找到这些元素时:

price = container.findAll("span",{"class":"a-size-small a-color-secondary a-text-strike"})

并且没有找到任何元素 - 这price是一个空列表。在下一行中,您访问 的第一个元素price

product_price = price[0].text.strip()

因为price它是空的,所以你会得到一个错误IndexError: list index out of range

例如,我在代码中的链接页面上有这样的元素:

在此处输入图像描述

您选择删除线价格,但一加 6T没有。它只有<span class="a-size-base a-color-price s-price a-text-bold">.

您可以检查是否price为空,如果是 - 您可以在span上面搜索价格。


推荐阅读