- 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 ""
リクエストを通じて https://2021.ip138.com/ をリクエストすると、そのタイトルはあなたの IP を返すだけなので、直接 bs4 に移動してタイトルの値を取得し、それを返すことができます. 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())
- コードを完成させ、対応するスレッドを作成してループを維持するだけです.私が使用すると、IPが1時間に1回変化するかどうかを検出するように定義されています.
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()