Selenium爬取日期存入MySQL显示0000-00-00问题求助
问题排查与解决办法
1. 日期格式不兼容MySQL DATE类型
MySQL的DATE类型要求严格遵循YYYY-MM-DD格式,但爬取到的日期是MM/DD(无年份),直接插入会被判定为无效日期,自动转为0000-00-00。
解决:补充年份(建议从页面获取,或取当前年份)并转换格式:
from datetime import datetime # 处理爬取到的日期(示例值:07/28) if first_registration: # 假设取当前年份,若页面有年份则替换为对应值 current_year = datetime.now().year month, day = first_registration.split('/') # 补零确保格式正确(如07而非7) first_registration = f"{current_year}-{month.zfill(2)}-{day.zfill(2)}"
2. 爬取代码存在语法错误
提供的爬取日期代码片段中,except块内first_registration =后无赋值内容,会触发语法错误,导致first_registration未被正确初始化,最终插入空值。
解决:补充默认值:
if "Test" in description_list: index_no = description_list.index("Test") try: first_registration = value_list[index_no] except: first_registration = "" # 或赋值为None
3. first_registration未从DataFrame中提取
在循环处理df_last的代码块中,仅初始化了first_registration = "",但未从chunk或df_last中提取对应字段的值,导致插入时始终为空字符串。
解决:根据df_last的列结构提取值:
# 假设df_last中存在first_registration列 if 'first_registration' in df_last.columns: col_index = df_last.columns.get_loc('first_registration') first_registration = chunk[0][col_index] else: first_registration = ""
4. SQL插入参数不匹配
插入语句定义了3个占位符%s,但val元组包含4个参数(brand_and_model, location, first_registration, download_date_time),会导致字段赋值错误或插入失败。
解决:修正占位符与参数数量一致:
# 若表中存在location字段,修改INSERT语句 mySql_insert_query = "INSERT INTO S (brand_and_model,location,first_registration,download_date_time) VALUES (%s,%s,%s,%s)" val = (brand_and_model, location, first_registration, download_date_time) # 若表中无location字段,移除该参数 mySql_insert_query = "INSERT INTO S (brand_and_model,first_registration,download_date_time) VALUES (%s,%s,%s)" val = (brand_and_model, first_registration, download_date_time)
5. download_date_time字段类型错误
表定义中download_date_time设为DATE(6),但代码中存入的是YYYYMMDD_HHMMSS格式的字符串,不符合DATE类型要求,同样会被转为0000-00-00。
解决:将字段类型改为DATETIME,并转换存储格式:
# 转换为MySQL DATETIME兼容格式 now = datetime.now() datetime_string = now.strftime("%Y-%m-%d %H:%M:%S") df_last['download_date_time'] = datetime_string
同时修正表定义:
sql = """CREATE TABLE S( brand_and_model VARCHAR(32), first_registration DATE, download_date_time DATETIME )"""
内容的提问来源于stack exchange,提问作者B.12
相关产品推荐
相关产品推荐

