如何用Python Pandas打印所有行及缺失日期对应的提示信息
问题原因
你在第二段构造DataFrame数据源rows的循环中,加入了if titleElement and priceElement and dateElement:的过滤条件,只要商品没有有效日期节点,整行数据就会被直接丢弃,自然最终输出的DataFrame就只会保留带明确日期的记录,和第一段直接打印的逻辑不一致。
修改方案
调整构造rows的逻辑,去掉对dateElement的强制存在判断:当dateElement不存在时,将日期字段值设为"The date is not available"即可,同时保留对title和price的存在判断(和第一段打印逻辑对齐,这两个字段为空的商品直接跳过)。
修改后的核心代码(仅需替换原第二段循环部分即可)
results.findAll("li") items = results.findAll("li") rows = [] for item in items: titleElement = item.find("h3") priceElement = item.find("span", {"class": "s-item__price"}) dateElement = item.find("span", {"class": "s-item__time-end"}) # 仅判断title和price必须存在,date可选 if titleElement and priceElement: newListingTag = titleElement.find("span", {"class": "LIGHT_HIGHLIGHT"}) if newListingTag: newListingTag.extract() # 处理日期字段,不存在就赋值提示文本 date_val = dateElement.text if dateElement else "The date is not available" row = [date_val, titleElement.text, priceElement.text] rows.append(row) import pandas as pd pd.set_option('expand_frame_repr', False) pd.set_option("display.max_rows", None, "display.max_columns", None, "display.max_colwidth", None) pd.set_option('display.max_colwidth', -1) df = pd.DataFrame.from_records(rows, columns=["Purchase Date", "Title", "Price"]) print(df)
修改后DataFrame的输出就会和第一段直接打印的条目数量完全一致,缺失日期的行也会显示对应的提示文本。
内容的提问来源于stack exchange,提问作者user16042028
相关产品推荐
相关产品推荐

