最近在處理網站內的圖片域名替換,由於大小專區網站衆多(上百個),各網站均用靜態文件發佈器創建後生成html,css,js文件,要替換文件特別多,域名均寫在頁面源碼裏或js,css文件內,純手工更改是不可能的,因此用python寫了一個圖片域名替換腳本進行批量替換,執行過程中也遇到過不少編碼格式、亂碼文件名等問題,但總算是完成了替換工作。
replace_2_7.py
# !/usr/bin/env Python
# coding=utf-8
# -*- coding: UTF-8 -*-
## python 2.7 網站靜態資源文件內容域名替換腳本
## 運行:python replace_2_7.py
# 因服務器默認安裝的是python2.7,沒有升級,如果是3.X,請註釋掉import sys、imp 等前四行
import sys
import imp
imp.reload(sys)
sys.setdefaultencoding('utf8')
from io import open
import os
# 讀取指定目錄下所有文件(此方法停用,os.walk()讀取目錄下如文件或文件夾亂碼命名、非utf-8文件加載,均會失敗,open_listdir兼容性強)
def open_dir(_dir, _dict):
for root, dirs, files in os.walk(_dir):
print('dir %s' % root) # 當前目錄路徑
# print(dirs) # 當前路徑下所有子目錄
# print(files) # 當前路徑下所有子文件
for file in files:
f_type = os.path.splitext(file)[1]
f_path = '%s/%s' % (root, file)
if f_type == '.html' or f_type == '.HTML' or f_type == '.js' or f_type == '.JS' or f_type == '.css' or f_type == '.CSS':
if skip_file(f_path) == 1:
replace_file(f_path, _dict)
# 讀取指定目錄下所有文件
def open_listdir(_dir, _dict):
_dirs = os.listdir(_dir)
for file in _dirs:
if file == 'music' or file == 'img' or file == 'images' or file == 'sound' or file == 'doc':
print('skip dir : %s' % file)
continue
f_path = '%s/%s' % (_dir, file)
if os.path.isdir(f_path):
print('dir : %s' % _dir)
open_listdir(f_path, _dict)
if os.path.isfile(f_path):
f_type = os.path.splitext(file)[1]
if f_type == '.html' or f_type == '.HTML' or f_type == '.js' or f_type == '.JS' or f_type == '.css' or f_type == '.CSS':
if skip_file(f_path) == 1:
replace_file(f_path, _dict)
# 檢驗是否跳過不替換的文件
def skip_file(f_path):
f_name = os.path.basename(f_path);
# print('%s name : %s' % (f_path, f_name))
skip_files = ['jquery.min.js', 'jquery.mousewheel.js', 'main.css']
for skip_f in skip_files:
if f_name == skip_f:
print('skip file : %s' % skip_f)
return 0
return 1
# 讀取域名替換文件
def open_txt(f_path):
_dict = {}
_lines = read_file(f_path, 'utf-8')
for line in _lines:
_strs = line.replace('\n', '').split(',')
_dict[_strs[0]] = _strs[1]
print('替換清單 %s' % _dict)
return _dict
# 查找替換的內容,並重寫文件內容
def replace_file(f_path, _dict):
_content = []
_lines = read_file(f_path, 'utf-8')
for _line in _lines:
_content.append(line_replace(_line, _dict))
if len(_content) > 0:
write_file(f_path, _content, 'utf-8')
print()
# 進行行比較與替換
def line_replace(_str, _dict):
_keys = _dict.keys()
for _k in _keys:
_i = _str.find(_k)
if _i != -1:
print('index = %s %s to %s' % (_i, _k, _dict[_k]))
_str = _str.replace(_k, _dict[_k])
return _str
# 讀取文件
def read_file(f_path, encoding):
print('read %s' % f_path)
f = None
try:
f = open(f_path, mode='r', encoding=encoding)
return f.readlines()
except UnicodeDecodeError:
if encoding == 'utf-8':
print('文件格式轉換錯誤,切換成gbk')
return read_file(f_path, 'gbk')
if encoding == 'gbk':
print('文件格式轉換錯誤,切換成gb2312')
return read_file(f_path, 'gb2312')
finally:
if f:
f.close()
return []
# 重新寫入文件
def write_file(f_path, _content, encoding):
print('write %s' % f_path)
f = None
try:
f = open(f_path, mode='w', encoding=encoding)
f.writelines(_content)
finally:
if f:
f.close()
# 入口
if __name__ == '__main__':
_dict = open_txt('/opt/app/domain.txt')
_dirs = read_file('/opt/app/www_dirs.txt')
for _dir in _dirs:
_dir = _dir.replace('\n', '')
open_listdir('/data/www/' + _dir, _dict)
print('%s 處理完畢...' % _dir)
print('全部替換,處理完畢...')
domain.txt
img1.old.xxx.com,img1.news.xxx.com
img2.old.xxx.com,img2.news.xxx.com
img3.old.xxx.com,img3.news.xxx.com
以逗號分隔,前面爲舊的域名,後面爲新的替換後的域名,如:img1.old.xxx.com替換爲img2.news.xxx.com
www_dirs.txt
a.xxx.com
b.xxx.com
c.xxx.com
...
此文件清單爲各個靜態網站在服務器上的存放目錄,統一放在/data/www目錄下,通過遍歷此目錄下所有網站文件進行批量圖片域替換;
執行腳本
# 在linux服務器上執行
python replace_2_7.py