import os from bs4 import BeautifulSoup if __name__ == '__main__': file_list = os.listdir("./mdbook_test/book") for item in file_list: full_path = os.path.join("./mdbook_test/book", item) if os.path.isfile(full_path) and item.endswith(".html"): with open(full_path, encoding="utf-8", mode="r") as file: content = file.read() soup = BeautifulSoup(content) if not soup.find(id="sidebar") == None: soup.find(id="sidebar").decompose() while soup.find("nav") is not None: soup.find("nav").decompose() while soup.find(class_="fa-search") is not None: soup.find(class_="fa-search").decompose() if not soup.find(id="search-wrapper") == None: soup.find(id="search-wrapper").decompose() with open(full_path, encoding="utf-8", mode="w+") as file: origin_str = soup.prettify() correct_str = origin_str.replace("http://localhost:8888/nbextensions/assets", ".") content = file.write(correct_str) print("已完成"+item)