response.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. This module provides some useful functions for working with
  3. scrapy.http.Response objects
  4. """
  5. import os
  6. import weakref
  7. import webbrowser
  8. import tempfile
  9. from twisted.web import http
  10. from scrapy.utils.python import to_bytes, to_native_str
  11. from w3lib import html
  12. _baseurl_cache = weakref.WeakKeyDictionary()
  13. def get_base_url(response):
  14. """Return the base url of the given response, joined with the response url"""
  15. if response not in _baseurl_cache:
  16. text = response.text[0:4096]
  17. _baseurl_cache[response] = html.get_base_url(text, response.url,
  18. response.encoding)
  19. return _baseurl_cache[response]
  20. _metaref_cache = weakref.WeakKeyDictionary()
  21. def get_meta_refresh(response, ignore_tags=('script', 'noscript')):
  22. """Parse the http-equiv refrsh parameter from the given response"""
  23. if response not in _metaref_cache:
  24. text = response.text[0:4096]
  25. _metaref_cache[response] = html.get_meta_refresh(text, response.url,
  26. response.encoding, ignore_tags=ignore_tags)
  27. return _metaref_cache[response]
  28. def response_status_message(status):
  29. """Return status code plus status text descriptive message
  30. """
  31. message = http.RESPONSES.get(int(status), "Unknown Status")
  32. return '%s %s' % (status, to_native_str(message))
  33. def response_httprepr(response):
  34. """Return raw HTTP representation (as bytes) of the given response. This
  35. is provided only for reference, since it's not the exact stream of bytes
  36. that was received (that's not exposed by Twisted).
  37. """
  38. s = b"HTTP/1.1 " + to_bytes(str(response.status)) + b" " + \
  39. to_bytes(http.RESPONSES.get(response.status, b'')) + b"\r\n"
  40. if response.headers:
  41. s += response.headers.to_string() + b"\r\n"
  42. s += b"\r\n"
  43. s += response.body
  44. return s
  45. def open_in_browser(response, _openfunc=webbrowser.open):
  46. """Open the given response in a local web browser, populating the <base>
  47. tag for external links to work
  48. """
  49. from scrapy.http import HtmlResponse, TextResponse
  50. # XXX: this implementation is a bit dirty and could be improved
  51. body = response.body
  52. if isinstance(response, HtmlResponse):
  53. if b'<base' not in body:
  54. repl = '<head><base href="%s">' % response.url
  55. body = body.replace(b'<head>', to_bytes(repl))
  56. ext = '.html'
  57. elif isinstance(response, TextResponse):
  58. ext = '.txt'
  59. else:
  60. raise TypeError("Unsupported response type: %s" %
  61. response.__class__.__name__)
  62. fd, fname = tempfile.mkstemp(ext)
  63. os.write(fd, body)
  64. os.close(fd)
  65. return _openfunc("file://%s" % fname)