HTML文件中lots数据转Pandas DataFrame报错:构造函数调用异常
解决从HTML的script标签提取"lots"数组并转为Pandas DataFrame的问题
错误原因
你直接传入字符串"lots"给pd.DataFrame(),这完全不符合构造函数的要求——DataFrame需要接收可迭代数据(比如列表、字典序列),而不是一个字符串。而且你根本没从HTML的script标签里提取到实际的lots数组数据。
解决方案步骤
- 提取script标签内的文本内容
- 精准匹配出
"lots"对应的数组片段 - 修复片段的JSON语法问题(原数据里的字符串值没有引号,不符合JSON规范)
- 将修复后的字符串转为Python列表,再创建DataFrame
完整代码
from bs4 import BeautifulSoup import pandas as pd import re import json html_doc = """<html><head><script> "unrequired_data = [{"ID":XXX, "Name":XXX, "Price":100GBP, "description": null }, {"ID":XXX, "Name":XXX, "Price":150GBP, "description": null }, {"ID":XXX, "Name":XXX, "Price":150GBP, "description": null }] "lots":[{"ID":123, "Name":ABC, "Price":100, "description": null }, {"ID":456, "Name":DEF, "Price":150, "description": null }, {"ID":789, "Name":GHI, "Price":150, "description": null }] </script></head></html>""" # 提取script标签文本 soup = BeautifulSoup(html_doc, "html.parser") script_text = soup.find("script").string.strip() # 匹配lots对应的数组片段 pattern = r'"lots":(\[.*?\])' match = re.findall(pattern, script_text, re.DOTALL)[0] # 修复JSON语法:给无引号的字符串值添加引号 fixed_json = re.sub(r'(\w+):(\w+)(?=[,}])', r'\1:"\2"', match) # 处理原数据中的占位符和带单位的价格 fixed_json = re.sub(r'XXX', '"XXX"', fixed_json) fixed_json = re.sub(r'(\d+)GBP', r'"\1GBP"', fixed_json) # 转为Python列表并生成DataFrame lots_data = json.loads(fixed_json) df = pd.DataFrame(lots_data) print(df)
输出结果
ID Name Price description 0 123 ABC 100 None 1 456 DEF 150 None 2 789 GHI 150 None
内容的提问来源于stack exchange,提问作者Owen
相关产品推荐
相关产品推荐

