使用Python和pandas批量发WhatsApp消息时astype错误的原因与解决
WhatsApp自动发送脚本报错分析与修复方案
错误原因
- 核心问题是调用了错误的方法:
data.loc[i,'Cellphone']获取的是单个Python原生int类型值,而astype()是pandas的Series/DataFrame对象专属方法,原生int对象没有这个属性,因此触发AttributeError。 - 小批量测试时正常的原因:大概率是测试用的Excel中手机号单元格为文本格式,读取后是str类型,调用
astype(str)不会报错;而1700+条数据的单元格是数字格式,被pandas识别为int类型,才暴露了这个逻辑错误。
修复方案
方案1:读取Excel时直接指定手机号列为字符串类型(推荐)
从源头上避免手机号被转为int类型,后续无需额外转换:
import pandas as pd import webbrowser as web import pyautogui as pg import time # 读取时指定Cellphone列为字符串 data = pd.read_excel("book1.xlsx", sheet_name='sheet1', dtype={'Cellphone': str}) for idx, row in data.iterrows(): cellphone = row['Cellphone'] message = "Test Message" web.open(f"https://web.whatsapp.com/send?phone={cellphone}&text={message}") time.sleep(5.5) pg.click(1230,964) time.sleep(1) pg.press('enter') time.sleep(2) pg.hotkey('ctrl', 'w') time.sleep(1)
方案2:对单个int值直接用Python原生str()转换
如果不想修改读取逻辑,直接把astype(str)替换为str():
# 替换原代码中的cellphone赋值行 cellphone = str(data.loc[i,'Cellphone'])
方案3:优化循环逻辑(可选,提升代码可读性)
用iterrows()遍历数据行,比range(len(data))更符合pandas的使用习惯:
for idx, row in data.iterrows(): cellphone = str(row['Cellphone']) # 若已指定dtype为str则直接用row['Cellphone'] # 后续逻辑不变
内容的提问来源于stack exchange,提问作者Federico Martinez
相关产品推荐
相关产品推荐

