如何用Python向WhatsApp用户发送PDF/图片文件?
解决方案:通过Python向WhatsApp发送PDF文件及文本消息
现有场景回顾
你已通过pywhatkit实现文本消息发送:
- 给个人客户发送:
pywhatkit.sendwhatmsg_instantly("Contact Number", "Text MSG") - 给群组发送:
pywhatkit.sendwhatmsg_to_group_instantly("Group ID", "Text MSG")
遇到的问题:
pywhatkit.sendwhats_image方法不存在,无法通过该模块直接发送媒体文件- 不想使用Twilio等第三方服务,因成本较高或仅支持向注册用户发送
以下是几种实用的替代方案:
方案1:pywhatkit + pyautogui 模拟人工操作
利用pywhatkit打开WhatsApp Web聊天窗口,再通过pyautogui模拟点击附件、上传PDF、输入文本的操作,适合小型场景快速实现。
示例代码:
import pywhatkit import pyautogui import time # 打开目标聊天窗口(空文本占位,仅触发窗口打开),等待页面加载完成 pywhatkit.sendwhatmsg_instantly("Contact Number", "", wait_time=10) time.sleep(2) # 模拟点击附件按钮(坐标需根据你的屏幕分辨率自行调整,可先用pyautogui.position()获取) pyautogui.click(x=1850, y=950) time.sleep(1) # 点击"文档"选项(坐标自行调整) pyautogui.click(x=1700, y=700) time.sleep(2) # 输入PDF绝对路径并确认上传 pyautogui.typewrite("C:/Documents/your_file.pdf") pyautogui.press("enter") time.sleep(3) # 输入文本说明并发送 pyautogui.typewrite("Hi, please check the attached PDF.") pyautogui.press("enter")
注意:运行过程中不要移动鼠标,避免干扰自动操作;不同屏幕的按钮坐标需自行校准。
方案2:使用WhatsApp官方Business API
如果是面向商业场景,官方API是最稳定的选择,支持发送文档(含PDF)和文本,无注册用户限制,成本按发送量计费,适合长期业务使用。
示例代码(依赖facebook-business库):
from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.whatsappmessage import WhatsAppMessage # 初始化API(需提前获取access_token、app_id、app_secret) FacebookAdsApi.init(access_token='your_access_token', app_id='your_app_id', app_secret='your_app_secret') # 构造并发送文档+文本消息 message = WhatsAppMessage( from_='your_whatsapp_business_number', to='customer_contact_number', type='document', document={'link': 'https://your-public-server.com/path/to/file.pdf'}, caption='Hi, here is the PDF you requested.' ) message.remote_create()
注意:需先完成WhatsApp商家账号验证、号码注册流程;PDF文件需放在公开可访问的HTTPS链接中。
方案3:Selenium 操控WhatsApp Web
用Selenium直接操控WhatsApp Web,比pyautogui更灵活,可自定义更多操作逻辑,适合需要批量处理或复杂场景的需求。
示例代码(简化版):
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time # 启动浏览器并打开WhatsApp Web driver = webdriver.Chrome() driver.get("https://web.whatsapp.com/") time.sleep(10) # 预留扫码登录时间 # 搜索目标客户/群组 search_box = driver.find_element(By.XPATH, '//div[@title="搜索输入框"]') search_box.send_keys("Contact Number/Group Name") search_box.send_keys(Keys.ENTER) time.sleep(2) # 点击附件按钮 attach_btn = driver.find_element(By.XPATH, '//div[@title="附加"]') attach_btn.click() time.sleep(1) # 上传PDF文件 doc_input = driver.find_element(By.XPATH, '//input[@accept="*"]') doc_input.send_keys("C:/Documents/your_file.pdf") time.sleep(3) # 输入文本说明并发送 msg_box = driver.find_element(By.XPATH, '//div[@title="输入消息"]') msg_box.send_keys("Hi, check out the attached PDF.") msg_box.send_keys(Keys.ENTER) driver.quit()
注意:WhatsApp Web的页面元素XPATH可能随版本更新变化,需定期检查调整;可通过保存cookie实现免重复扫码登录。
内容的提问来源于stack exchange,提问作者Anil Daderwal
相关产品推荐
相关产品推荐

