Python Glossary English

все Python 3urllib.requestфункция

urllib.request.urlopen()

открытие URL

Открывает URL (http, https, ftp, file, data) или объект Request и возвращает файлоподобный ответ, который читается байтами.

Синтаксис

urllib.request.urlopen(url, data=None, timeout=..., *, context=None)

read() возвращает bytes, а не str: текст надо декодировать, кодировку подскажет resp.headers.get_content_charset(). Без timeout запрос к зависшему серверу ждёт бесконечно — передавайте timeout явно. Ответ 4xx/5xx не возвращается, а поднимается как urllib.error.HTTPError (у него тоже есть .code и .read()), а строка без схемы вроде 'example.com' даёт ValueError. Ответ закрывайте через with.

Примеры

import pathlib, urllib.request
path = pathlib.Path('hello.txt')
path.write_text('Привет', encoding='utf-8')
with urllib.request.urlopen(path.resolve().as_uri()) as resp:
    data = resp.read()
print(type(data).__name__, data.decode('utf-8'))  # → bytes Привет
import urllib.request
with urllib.request.urlopen('data:text/plain;charset=utf-8,Hello%20World') as resp:
    print(resp.read(), resp.headers.get_content_charset())  # → b'Hello World' utf-8
urllib.request.urlopen('example.com')  # → ValueError: unknown url type: 'example.com'

См. также

Частые ошибки

Открыть в полном глоссарииdocs.python.orgСообщить о неточности