from bs4 import BeautifulSoup
with open('test.xml') as reader:
xml = reader.read()
deleted_id = []
with open('delete.txt') as reader:
for line in reader:
line = line.strip()
deleted_id.append(line)
def has_delete_id(tag):
return tag.name=='re' and tag.id.string in deleted_id
soup = BeautifulSoup(xml, 'html.parser')
tags = soup(has_delete_id)
for tag in tags:
tag.decompose()
print(soup.prettify())
你可以使用
BeautifulSoup套件:安裝:
如果覺得
html解析器不敷使用,參考文檔安裝其他適合的解析器。如果想要詳細了解
BeautifulSoup也請參考官方文檔(有中文版本)。測試檔:
以下是我使用的測試文件:
代碼:
程式輸出:
代碼說明:
首先我們從
Beautiful Soup的套件中匯入BeautifulSoup類接著分別從
delete.txt和test.xml中讀出要刪除的 id 和主要的 xml 內容,下一步是實體化生成一個BeautifulSoup對象soup, 我們採用html.parser解析器去解析xml:在此我們定義了一個用於過濾的 function
has_delete_id,每一個在xml中的tag 只要是<re>tag 且含有想要刪除的<id>tag 就會被檢索出來:接著
soup(has_delete_id)會幫助我們找到欲刪除的 tag,接著走訪搜索出來的這些 tag 並呼叫方法decompose()來從文件中刪除該標籤。最後
soup.prettify()可以幫助我們輸出修改後的文件。