【问题标题】:Python3 with urllib and accent带有 urllib 和口音的 Python3
【发布时间】:2013-03-28 03:25:15
【问题描述】:

我尝试访问带有重音符号的 URL,但没有成功:

#!/usr/bin/python3.3
# -*- coding: utf-8 -*- 

import urllib.request

response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?city=Lévis&format=json")
content = response.read()
print(content)

当我执行此代码时,我会返回此错误

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 22: ordinal not in range(128)

所以我试试这个

response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?city=Lévis&format=json".encode("UTF-8"))

但还是报错

AttributeError: 'bytes' object has no attribute 'timeout'

你知道我的错误在哪里吗?

【问题讨论】:

标签: python encoding character-encoding python-3.x urllib


【解决方案1】:

你需要转义你的查询参数,就像@Cairnarvon 说的:

import urllib.parse

city = 'Lévis'
query = "city=%s&format=json" % (urllib.parse.quote(city),)
response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?" + query)

【讨论】:

    猜你喜欢
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 2018-08-17
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多