You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium爬取的油价如何正确填入smtplib发送的Gmail邮件正文

问题解决方案

错误原因

你当前代码的问题出在conn.sendmail()的第三个参数配置:你把price直接写在了硬编码的字符串里,Python不会自动解析普通字符串里的变量名,所以只会把"price"这个字符串本身作为内容发送,无法匹配你爬取到的实际价格。

修复方法

替换conn.sendmail对应的代码行即可,两种常用实现方式可选:

方式1:f-string拼接(Python3.6+版本推荐,写法最简洁)

conn.sendmail('example@mail.com', 'example2@mail.com', f'Subject: Best Petrol Price in Perth today is: {price}\n\n{price}')

方式2:format格式化(兼容低版本Python)

conn.sendmail('example@mail.com', 'example2@mail.com', 'Subject: Best Petrol Price in Perth today is: {}\n\n{}'.format(price, price))

可选优化

你可以提前把邮件内容封装成独立变量,后续修改调试更方便:

subject = f"Best Petrol Price in Perth today is: {price}"
body = price
full_msg = f"Subject: {subject}\n\n{body}"
conn.sendmail('example@mail.com', 'example2@mail.com', full_msg)

注:你当前代码里主题和正文之间的两个换行符\n\n写法是正确的,保留即可,不要删掉,否则会出现邮件内容识别为空的问题。

内容的提问来源于stack exchange,提问作者All

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 13:45:04