慕桂英3389331
2021-07-04 14:14:45
首先,我關(guān)注了這個問題,但我仍然對 remove 方法有問題。tag.getparent().remove(tag)我使用這段代碼刪除 了此網(wǎng)頁中具有屬性name="2" 和 id = "2" 的錨標記當該行被執(zhí)行時,我仍然能夠看到標簽及其屬性,當我遍歷所有孩子時,我仍然能夠看到我刪除的元素remove 方法究竟做了什么,為什么被刪除的標簽仍然存在?這是該行執(zhí)行后調(diào)試器的屏幕截圖。
1 回答

侃侃爾雅
TA貢獻1801條經(jīng)驗 獲得超16個贊
當您從其父節(jié)點中刪除節(jié)點時,該節(jié)點本身仍然存在,但只是與父節(jié)點分離。這允許您將“已刪除”節(jié)點附加到不同的父節(jié)點。但是,如果您不將節(jié)點附加到新的父節(jié)點,那么從根節(jié)點的角度來看,該節(jié)點與刪除一樣好。
為了保留被移除的標簽節(jié)點的子節(jié)點,你可以像這樣在相同的索引處將它們修剪到標簽的父節(jié)點:
parent = tag.getparent()
index = parent.index(tag)
for child in tag.getchildren()[::-1]: # in reverse order so that we can keep inserting at the same index while preserving the original order
tag.remove(child)
parent.insert(index, child)
parent.remove(tag)
或者您可以簡單地使用該drop_tag方法:
tag.drop_tag()
添加回答
舉報
0/150
提交
取消