You need to enable JavaScript to run this app. 如何用Python Pandas打印所有行及缺失日期对应的提示信息
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 10:06:04