python - 网页抓取列表索引超出范围
问题描述
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索引超出范围)。请,有人可以解释我在哪里做错了吗?
解决方案
不是每个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
上面搜索价格。
推荐阅读
- r - 指定 as.Date 格式在 R 中返回 NA
- sql - 以 1900-01-01 为日期的 SQL 表
- airflow - 作曲家自动缩放?
- php - PHP 5.3 - 如何在不加载到内存的情况下将内容附加到大文件
- ios - 在 CollectionView 中估计单元格高度的更快方法
- java - String.compareIgnoreCase 返回错误结果
- mysql - MySQL 在 where 子句中不等于 >= '' 吗?哪个表现更好?
- tomcat - 升级后Alfresco登录问题
- java - 如何将 JFreeChart 的图形保存在 PNG 图像中?
- neo4j - neo4j 事务日志未修剪