D:\PythonProject\.venv\Scripts\python.exe D:\PythonProject\jd_book_crawler.py Traceback (most recent call last): File "D:\PythonProject\jd_book_crawler.py", line 73, in <module> main() File "D:\PythonProject\jd_book_crawler.py", line 69, in main save_to_csv(all_phones[:target_count]) # 只保留前1000条有效数据 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\PythonProject\jd_book_crawler.py", line 38, in save_to_csv keys = data[0].keys() ~~~~^^^ IndexError: list index out of range 进程已结束,退出代码为 1
时间: 2025-05-30 14:57:17 浏览: 15
### 解决Python爬虫中`IndexError: list index out of range`问题
当运行爬虫程序时遇到`IndexError: list index out of range`错误,通常是因为尝试访问一个空列表中的元素。这种问题可能发生在多个场景中,比如HTML解析失败、目标网站结构调整或数据未成功抓取等情况。
以下是对该问题的具体分析和解决方案:
#### 错误原因
1. **HTML结构变化**:如果目标网站的HTML结构发生了更改,可能导致原本预期存在的标签无法找到,从而返回空列表[^1]。
2. **数据缺失**:部分页面可能缺少特定字段的数据,导致在遍历过程中试图访问不存在的索引位置。
3. **初始条件不足**:例如,在调用`save_to_csv`函数时传入了一个空的`data`列表,这可能是由于前面的抓取阶段未能正确填充数据所致。
#### 修改后的代码实现
为了增强代码健壮性,可以采取如下改进措施:
```python
def fetch_phone_data(url):
""" 获取单页上的所有手机信息 """
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
phones = []
items = soup.find_all('div', class_='phone-item') # 替换为实际网站对应的HTML结构
if not items: # 检查是否有任何项目被找到
print(f"No data found on the page {url}. Skipping...")
return phones
for item in items:
name_tag = item.find('h2')
price_tag = item.find('span', class_='price')
brand_tag = item.find('span', class_='brand')
# 添加额外的安全检查以避免NoneType对象的操作
name = name_tag.text.strip() if name_tag else "N/A"
price = price_tag.text.strip() if price_tag else "N/A"
brand = brand_tag.text.strip() if brand_tag else "N/A"
phone_info = {
'Name': name,
'Price': price,
'Brand': brand
}
phones.append(phone_info)
return phones
except Exception as e:
print(f"An error occurred while fetching data from {url}: {e}")
return [] # 返回空列表以防中断整个流程
def save_to_csv(data, filepath=r'D:\Python\save\phones.csv'):
""" 将数据保存至CSV文件 """
if not data: # 在写入前先验证数据是否存在
print("No data available to write into CSV file.")
return
keys = data[0].keys()
with open(filepath, 'w', newline='', encoding='utf-8-sig') as output_file:
dict_writer = csv.DictWriter(output_file, fieldnames=keys)
dict_writer.writeheader()
dict_writer.writerows(data)
def main():
base_url = 'https://example.com/phones?page={}'
all_phones = []
current_count = 0
target_count = 1000
while current_count < target_count:
page_num = int(current_count / 20) + 1
url = base_url.format(page_num)
new_phones = fetch_phone_data(url)
if not new_phones: # 如果新获取的数据为空则跳过本次循环
print(f"No more data fetched from {url}. Stopping further attempts.")
break
all_phones.extend(new_phones)
current_count += len(new_phones)
print(f"Fetched {current_count} records so far.")
time.sleep(random.uniform(1, 3))
save_to_csv(all_phones[:target_count])
print("Data collection completed and saved to CSV file at D:\\Python\\save.")
if __name__ == "__main__":
main()
```
#### 改进要点说明
1. **增加异常处理**:对于可能出现的各种意外情况(如网络超时、连接失败),都应设置相应的异常捕捉逻辑,并提供友好的提示信息以便于调试[^2]。
2. **安全检查机制**:每次执行关键操作之前都要确认前置条件是否满足,尤其是涉及外部资源读取的部分更需谨慎对待。
3. **日志记录优化**:通过打印必要的状态更新消息帮助开发者了解程序进展状况的同时也便于定位潜在的问题所在。
---
阅读全文
相关推荐


