- 定义get_ip的函数
def get_ip():
try:
url = 'https://2021.ip138.com/'
kv = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
par = {"prd": "resoukuang"}
html = requests.get(url=url, headers=kv, params=par).text
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.string
return title
except:
return ""
通过requests请求 https://2021.ip138.com/ , 因为它的标题刚好就返回了你的IP 那么我们直接bs4去取到title的值 返回即可
2. 定义发送邮件的函数
def mail(content):
# 发送者的邮箱地址
sender = '发送者的邮箱地址'
# 接收者的邮箱地址
receivers = ['接收者的邮箱地址1', '接收者的邮箱地址2']
# content是你要发送的内容, 我这里是调用函数穿过来的参数content
message = MIMEText(content, _subtype='plain', _charset='utf-8')
# 邮件的发送者
message['From'] = Header(sender, 'utf-8')
# 邮件的接收者
message['To'] = Header('coolwoow', 'utf-8')
# 邮件的标题
message['Subject'] = Header('主人, 你家里面的IP又变了:', 'utf-8')
smtper = SMTP('smtp.qq.com')
# QQ邮箱smtp的授权码
smtper.login(sender, 'QQ邮箱smtp的授权码')
smtper.sendmail(sender, receivers, message.as_string())
- 完整代码, 建立相应的线程去一直循环就可以了, 我使用的时候是定义的1小时检测一次IP是否发生变化
import requests
import threading
from bs4 import BeautifulSoup
from smtplib import SMTP
from email.header import Header
from email.mime.text import MIMEText
import time
def get_ip():
try:
url = 'https://2021.ip138.com/'
kv = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
par = {"prd": "resoukuang"}
html = requests.get(url=url, headers=kv, params=par).text
soup = BeautifulSoup(html, 'html.parser')
title = soup.title.string
return title
except:
return ""
def mail(content):
# 发送者的邮箱地址
sender = '发送者的邮箱地址'
# 接收者的邮箱地址
receivers = ['接收者的邮箱地址1', '接收者的邮箱地址2']
# content是你要发送的内容, 我这里是调用函数穿过来的参数content
message = MIMEText(content, _subtype='plain', _charset='utf-8')
# 邮件的发送者
message['From'] = Header(sender, 'utf-8')
# 邮件的接收者
message['To'] = Header('coolwoow', 'utf-8')
# 邮件的标题
message['Subject'] = Header('主人, 你家里面的IP又变了', 'utf-8')
smtper = SMTP('smtp.qq.com')
# QQ邮箱smtp的授权码
smtper.login(sender, 'QQ邮箱smtp的授权码')
smtper.sendmail(sender, receivers, message.as_string())
# 这里我用一个txt存放上次获取到的值得, 你可以事先把上面get_ip()的结果存在里面
f = open('ip.txt', 'r', encoding='utf-8')
old_ip = f.read()
f.close()
def main():
global old_ip
while True:
if get_ip() != "":
if old_ip != get_ip():
old_ip = get_ip()
mail(old_ip)
with open('ip.txt', 'w') as f:
f.write(old_ip)
time.sleep(120)
thread_run = threading.Thread(target=main)
thread_run.start()