为何pd.read_html获取对象调用info()报错?AttributeError问题求解
解决
AttributeError: 'list' object has no attribute info()的问题 Hey there! Let's break down why you're hitting this error and fix it step by step.
问题根源
The core issue lies in how pd.read_html() works: it doesn't return a single DataFrame directly. Instead, it gives you a list of DataFrames—since a webpage might have multiple HTML tables. When you called .info() on ca_colleges, you were trying to run a DataFrame-specific method on a plain list, which doesn't have that attribute. That's exactly why you got the AttributeError.
修复步骤
- Check how many tables were fetched: Use
len(ca_colleges)to see how many tables the function found on the page. - Pick the table you need: Access the target table from the list using index notation (like
ca_colleges[0]for the first table). - Assign it to a dedicated DataFrame variable: This makes your code cleaner and easier to work with.
- Call
.info()on the DataFrame: Now it'll run without errors!
修正后的代码示例
import pandas as pd import numpy as np import seaborn as sns url = "http://www.collegesimply.com/colleges/california/" ca_colleges = pd.read_html(url) # 查看抓取到的表格数量 print(f"共找到 {len(ca_colleges)} 个表格") # 选取第一个表格并转为DataFrame对象 ca_colleges_df = ca_colleges[0] # 现在可以正常调用info()方法了 ca_colleges_df.info()
额外小技巧
If you're unsure which table in the list is the one you want, preview each table's first few rows using .head():
# 预览第一个表格内容 print(ca_colleges[0].head()) # 预览第二个表格内容(如果存在的话) print(ca_colleges[1].head())
内容的提问来源于stack exchange,提问作者Ganci Sun
相关产品推荐
相关产品推荐

