【问题标题】:Unicode / Umlauts in urllib.request XML parsingurllib.request XML 解析中的 Unicode / 元音变音
【发布时间】:2017-06-03 23:31:57
【问题描述】:

我正在为 urllib.request 和 unicode 苦苦挣扎。我有一个脚本,它获取城市名称列表,从中构建 geonames.org API 请求 URL,并解析输出 XML 数据以完全按照我需要的方式显示地名信息。只要城市名称不包含任何非 ASCII 字符(如科隆中的 ö),脚本就可以正常工作(我必须使用德国城市名称)。

# -*- coding: utf-8 -*-
import urllib.request
from xml.etree import ElementTree as ET

urllist = []
citylist = ['Hamburg', 'Bremen']

for city in citylist:
    requestURL = 'http://api.geonames.org/search?name=' + city + '&maxRows=1&lang=de&username=demo'
    urllist.append(requestURL)

for url in urllist:
    root = ET.parse(urllib.request.urlopen(url)).getroot()
    items = root.findall('geoname')
    for item in items:
        print(item.find('name').text + ', ' + item.find('countryName').text + ' [' + item.find('lat').text + ',' + item.find('lng').text + '] [id:' + item.find('geonameId').text + ']')

当我用Köln 切换Hamburg 时,脚本退出并显示错误消息UnicodeEncodeError: 'ascii' codec can't encode character '\xf6' in position 18: ordinal not in range(128)

另一件不起作用的事情是城市名称中带有空格,例如Bad Godesberg。我是使用错误的方法来请求 XML,还是我必须在构建 URL 之前解码我的城市名称(这几乎肯定是两个词城市的情况,因为当我使用 Bad%20Godesberg 时它可以工作)?

感谢您的帮助!

【问题讨论】:

    标签: python unicode urllib


    【解决方案1】:

    例如,您必须使用urlencode

    Python » 文档21.8.4. URL Quoting

    这是一个使用 GET 方法检索包含参数的 URL 的示例会话:
    urllib-examples

       >>> import urllib.request
       >>> import urllib.parse
       >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
       >>> url = "http://www.musi-cal.com/cgi-bin/query?%s" % params
       >>> with urllib.request.urlopen(url) as f:
               print(f.read().decode('utf-8'))
    

    【讨论】:

    • 谢谢你,我要去看看 urlencode!与此同时,我尝试在 Juypter Notebooks 中运行我的代码,它神奇地工作,没有任何我无法解释但现在非常完美的更改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    相关资源
    最近更新 更多