从 urllib python 保存 XML 字符串

Save XML string from urllib python

我正在尝试保存从 Url(来自 google 映射 API)中获取的 xml,但我得到的参数必须是 str,而不是字节,这是代码

con=urllib.request.urlopen("https://maps.googleapis.com/maps/api/geocode/xml?address=Limon,CR&key=AIzaSyBeR0hUS1myPd7oa2LjJ2F6Vl37b-rUfVo")
def saveXml:
    data=con.read()
    f=open("xml2.xml","a")
    f.write(data)

要么以二进制模式打开文件:

def saveXml():
    data = con.read()
    with open('xml2.xml', 'ab') as f:
        f.write(data)

或者将二进制数据转换为文本(如果您知道编码是 UTF-8。)

def saveXml():
    data = con.read().decode('UTF-8')
    with open('xml2.xml', 'a') as f:
        f.write(data)