本帖最后由 iloong 于 2024-7-25 11:38 编辑
[Python] 纯文本查看 复制代码 import requests
import ipaddress
import os
import re
def get_ip138_ip(url,head):
response = requests.get(url=url,headers=head)
con_1 = response.text
#print(re)
obj = re.compile(r'<title>您的IP地址是:(?P<ipname>.*?)</title>')
#result = obj.finditer(con_1)
result = obj.finditer(con_1)
for it in result:
get_ip=it.group("ipname")
return get_ip
def replace_ips_in_file(file_path, old_ip, new_ip):
# 定义IP正则表达式
ip_pattern = r'\b(?:[0-9{1,3}\.){3}[0-9{1,3}\b'
# 读取文件内容
with open(file_path, 'r') as file:
content = file.read()
# 查找所有IP并替换
ip_regex = re.compile(ip_pattern)
new_content = ip_regex.sub(new_ip, content)
# 将新内容写回文件
with open(file_path, 'w') as file:
file.write(new_content)
url = 'https://2024.ip138.com/'
head = {
"User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"
}
get_ip = get_ip138_ip(url,head) #获取到ip138接口ip地址
file_path = './baidu.txt' # 替换为你的文本文件路径
ips = None
if ips == get_ip:
ips = get_ip
#replace_ips_in_file(file_path,ips,get_ip)
elif ips != get_ip:
replace_ips_in_file(file_path,ips,get_ip)
else:
ips = 'xx.xx.xx.xx' #文本内旧ip地址
replace_ips_in_file(file_path,ips,get_ip)
print(get_ip) |