Не может открыть Unicode URL with Python

Используя Python 2.5.2 и Linux Debian, я пытаюсь получить содержание от испанского URL, который содержит испанский символ 'í':

import urllib
url = u'http://mydomain.es/índice.html'
content = urllib.urlopen(url).read()

Я получаю эту ошибку:

UnicodeEncodeError: кодек 'ASCII' не может закодировать символьный u '\xe1' в положении 8: порядковый не в диапазоне (128)

Я попытался использовать прежде, чем передать URL urllib это:

url = urllib.quote(url)

и это:

url = url.encode('UTF-8')

но они не работали.

Можно ли сказать мне, что я делаю неправильно?

9
задан akinuri 16 April 2019 в 08:00
поделиться

4 ответа

Per the applicable standard, RFC 1378, URLs can only contain ASCII characters. Good explanation here, and I quote:

"...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL."

As the URLs I've given explain, this probably means you'll have to replace that "lowercase i with acute accent" with `%ED'.

3
ответ дан 4 December 2019 в 12:18
поделиться

This works for me:

#!/usr/bin/env python
# define source file encoding, see: http://www.python.org/dev/peps/pep-0263/
# -*- coding: utf-8 -*-

import urllib
url = u'http://example.com/índice.html'
content = urllib.urlopen(url.encode("UTF-8")).read()
7
ответ дан 4 December 2019 в 12:18
поделиться

У меня это работает. Убедитесь, что вы используете довольно свежую версию Python и кодировка вашего файла верна. Вот мой код:

# -*- coding: utf-8 -*-
import urllib
url = u'http://mydomain.es/índice.html'
url = url.encode('utf-8')
content = urllib.urlopen(url).read()

(mydomain.es не существует, поэтому поиск в DNS завершается неудачно, но в этом случае проблем с Unicode нет.)

3
ответ дан 4 December 2019 в 12:18
поделиться

Encoding the URL as utf-8, should have worked. I wonder if your source file is properly encoded, and whether the interpreter knows it. If your python source file is saved as UTF-8, for example, then you should have

# coding=UTF-8

as the first or second line.

import urllib
url = u'http://mydomain.es/índice.html'
content = urllib.urlopen(url.encode('utf-8')).read()

works for me.

Edit: also, be aware that Unicode text in an interactive Python session (whether through IDLE, or a console) is fraught with encoding-related difficulty. In those cases, you should use Unicode literals (like \u00ED in your case).

4
ответ дан 4 December 2019 в 12:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: