[英]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.