我想删除此Html文件中的特定行。我想查看字符串STARTDELETE的位置,并从那里删除+1到字符串ENDDELETE -1
我已使用' xxx'标记要删除的行为了更好地理解。我怎么能用python做到这一点?
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Image Gallery</h2>
<div class="row"> <!--STARTDELETE-->
xxx<div class="col-xs-3">
xxx<div class="thumbnail">
xxx<a href="/w3images/lights.jpg" target="_blank">
xxx<img style="padding: 20px" src="xxx" alt="bla" >
xxx<div class="caption">
xxx<p>Test</p>
xxx</div>
xxx</a>
xxx</div>
xxx</div>
</div> <!--ENDDELETE-->
</div>
</body>
</html>
答案 0 :(得分:1)
您可以先将该代码复制并粘贴到输入文件中,也可以命名为“input.txt”,然后将要保留的行输出到“output.txt”。忽略要删除的行。
w = open("output.txt", "w") # your output goes here
delete = False
with open("input.txt") as file:
for line in file:
if "<!--ENDDELETE-->" in line:
delete = False # stops the deleting
if not delete:
w.write(str(line))
if "<!--STARTDELETE-->" in line:
delete = True # starts the deleting
w.close() # close the output file
希望这有帮助!
答案 1 :(得分:1)
安装beautifulsoup4(HTML解析器/ DOM操纵器)
阅读数据,得到一个&#34; DOM&#34; (有一种可步行的结构)和beautifulsoup,取出你想要空的物品,remove its children。
在您的示例中,您似乎要清空其<div>(s)
的{{1}},对吧?我们假设您的HTML数据存储在一个名为class=row
的文件中(这可能与您的特定情况不一样......它会成为请求的正文或其他内容像那样)
data.html
输出:
from bs4 import BeautifulSoup
with open('data.html', 'r') as page_f:
soup = BeautifulSoup(page_f.read(), "html.parser")
# In `soup` we have our "DOM tree"
divs_to_empty = soup.find("div", {'class': 'row'})
for child in divs_to_empty.findChildren():
child.decompose()
print(soup.prettify())
如果您要进行DOM操作,我强烈建议您阅读并使用美丽的汤(它非常强大)