[英]Remove unnecessary tag content from html source using scrapy
我正在使用scrapy提取网页的html源,并将输出保存为.xml格式。 该网页源具有以下内容
<html>
<head>
<script type="text/javascript">var startTime = new Date().getTime();
</script><script type="text/javascript">var startTime = new
Date().getTime(); </script> <script type="text/javascript">
document.cookie = "jsEnabled=true";..........
...........<div style="margin: 0px">Required content</div>
</head>
</html>
从这个我需要删除所有
<script>....</script>
标签,并保留带有各自标签的所需内容。 我该如何使用scrapy?
我建议您使用lxml
包删除元素。
import lxml.etree as et
from lxml.etree import HTMLParser
from StringIO import StringIO
def parse(self, response):
parser = HTMLParser(encoding='utf-8', recover=True)
tree = et.parse(StringIO(response.body), parser)
for element in tree.xpath('//script'):
element.getparent().remove(element)
print et.tostring(tree, pretty_print=True, xml_declaration=True)
下面的代码删除文本中的1 div。
from bs4 import BeautifulSoup
from bs4.element import Tag
markup = '<a>This is not div <div class="1">This is div 1</div><div class="2">This is div 2</div></a>'
soup = BeautifulSoup(markup,"html.parser")
for tag in soup.select('div.1'):
tag.decompose()
print(soup)
输出:
<a>This is not div <div class="2">This is div 2</div></a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.