Advertisement
JPablos

urllib.request. Simple. Python

Jun 5th, 2022
1,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3.  
  4. # ==================================================================
  5. # Descarga una copia del `url` y la guarda en `/tmp`
  6. # Sí la página no está disponible, devuelve: `HTTPError: Forbidden`.
  7. #
  8. # Devuelve un objeto con una interfaz similar a un archivo;
  9. # el nombre del archivo es accesible mediante su atributo 'name'.
  10. # El archivo se eliminará automáticamente cuando se cierre,
  11. # a menos que el argumento 'delete' se establezca en `False`.
  12. #
  13. # El atchivo se crea en '/tmp' con un nombre arbitrario, sin
  14. # estensión, con 'tipo: documento HTML (text/html)'
  15. # En el ejemplo: el manual de usuario de `git`
  16. # =================================================================
  17.  
  18. import shutil
  19. import tempfile
  20. import urllib.request
  21.  
  22. with urllib.request.urlopen(
  23.         'https://mirrors.edge.kernel.org/pub/software/scm/git/docs/user-manual.html'
  24. ) as response:
  25.  
  26.     with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
  27.         shutil.copyfileobj(response, tmp_file)
  28.  
  29. with open(tmp_file.name, encoding='utf-8') as html:
  30.     pass
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement