Alo*_*hor 0 python sitemap parsing stream gunzip
我想解析压缩的站点地图,如www.example.com/sitemap.xml.gz,并收集站点地图中的所有网址,而不下载sitemap.xml.gz.
在下载sitemap.xml.gz并借助lxml或beautifulsoup等解压缩后,有办法解析它.
def parse_sitemap_gz(url):
r = requests.get(url, stream=True)
if 200 != r.status_code:
return False
file_name = url.split('/')[-1]
# download the sitemap file
with open(file_name, 'wb') as f:
if not r.ok:
print 'error in %s'%(url)
for block in r.iter_content(1024):
if not block:
break
f.write(block) # can I parse it without writing to file
f.flush()
# decompress gz file
subprocess.call(['gunzip', '-f', file_name])
# parse xml file
page = lxml.html.parse(file_name[0:-3])
all_urls = page.xpath('//url/loc/text()')
#print all_urls
# delete sitemap file now
subprocess.call(['rm', '-rf', file_name[0:-3]])
return all_urls
Run Code Online (Sandbox Code Playgroud)
在这段代码中我将压缩的站点地图写入文件.我的意图是不写任何文件.
为了学习和创建上述代码的智能版本,我如何解析它与解压缩gzip流的概念,所以我不需要下载文件或将其写入文件?
如果唯一的要求是不写入磁盘,并且gzip的文件没有只有该gunzip实用程序支持并适合内存的任何扩展,那么您可以从以下开始:
import requests
import gzip
from StringIO import StringIO
r = requests.get('http://example.com/sitemap.xml.gz')
sitemap = gzip.GzipFile(fileobj=StringIO(r.content)).read()
Run Code Online (Sandbox Code Playgroud)
然后解析sitemap过lxml,你是...
请注意,它不会"迭代"迭代器,因为您可能只需要在单个请求中获取整个文件.