大家好,谢谢您的宝贵意见。我通常会找到帮助,所以这是我的第一个问题。经过很长时间,我设法从这段代码中得到了有用的回复。许多文章不适用于python3。
import re
import json
import urllib.request, urllib.error, urllib.parse
import hashlib
import uuid
#! /usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
html = urlopen("http://ipinfo.io/json")
#result = html(buf.decode('utf-8'))
print(html.read())
回复以这种形式出现。
b'{\n "ip": "84.0.23.49",\n "hostname": "cpc127884-ldry4-2-0-
cust47.know.cable.virginm.net",\n "city": "London",\n "region":
"UK",\n "country": "GB",\n "loc": "54.9971,-7.3073",\n "org":
"AS5089 Virgin Media Limited",\n "postal": "BT34",\n "timezone":
"Europe/London",\n "readme": "https://ipinfo.io/missingauth"\n}'
我不知道这是我的位置或互联网服务,还是它的RPi,或者这可能是新格式。顺便说一句,我改变了一些位置的细节。但是这些文章似乎都没有描述如何以这种形式获取信息。通常看起来不一样。尝试时出现很多错误-例如,告诉我数据是二进制的而不是str我如何从这个“词典”中获得位置或城市?
使用json.loads()
函数来解析json响应(您将获得Python dict):
import json
from urllib.request import urlopen
html = urlopen("http://ipinfo.io/json")
d = json.loads(html.read().decode('utf-8'))
print(d['city'])
打印(以我为例):
Bratislava