From 13be33f0e75f46a1bdd60fda8518a6a3e6d100a7 Mon Sep 17 00:00:00 2001 From: Pablo Hoffman Date: Thu, 27 Aug 2009 18:20:51 -0300 Subject: [PATCH] added open_in_browser function to scrapy.utils.response --- scrapy/utils/response.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/scrapy/utils/response.py b/scrapy/utils/response.py index 842b36784..dd6c5123c 100644 --- a/scrapy/utils/response.py +++ b/scrapy/utils/response.py @@ -3,13 +3,16 @@ This module provides some useful functions for working with scrapy.http.Response objects """ -import re, weakref +import re +import weakref +import webbrowser +from tempfile import NamedTemporaryFile from twisted.web import http from twisted.web.http import RESPONSES from scrapy.xlib.BeautifulSoup import BeautifulSoup -from scrapy.http.response import Response +from scrapy.http import Response, HtmlResponse def body_or_str(obj, unicode=True): assert isinstance(obj, (Response, basestring)), "obj must be Response or basestring, not %s" % type(obj).__name__ @@ -72,3 +75,18 @@ def response_httprepr(response): s += "\r\n" s += response.body return s + +def open_in_browser(response): + """Open the given response in a local web browser, populating the + tag for external links to work + """ + # XXX: this implementation is a bit dirty and could be improved + if not isinstance(response, HtmlResponse): + raise TypeError("Unsupported response type: %s" % \ + response.__class__.__name__) + body = response.body + if '', '' % response.url) + with NamedTemporaryFile(suffix='.html', delete=False) as f: + f.write(body) + webbrowser.open("file://%s" % f.name)