我正在制作手机追踪器,我希望能够整理来自response.content的所有信息。
我已经尝试过进行print(response.content [9:13])(例如),但是我意识到每个电话号码都会有不同的位置,并且无法正确容纳
if valid_confirm_loop=='valid':
print('Number is Valid')
print('Country Prefix: ' + response.text[121:123])
print('Country code: ' + response.text[141:143])
print('Country Name: ' + response.text[161:185])
print("City: " + response.text[199:206])
{“有效”:true,“数字”:“ xxxxxxxxxxx”,“ local_format”:“ xxxxxxxxxxx”,“ international_format”:“ xxxxxxxxxxx”,“ country_prefix”:“ + 1”,“ country_code”: “ US”,“ country_name”:“美利坚合众国”,“位置”:“西雅图”,“运营商”:“ Cellco Partnership(Verizon Wireless)”,“ line_type”:“ mobile”} >
以上是我进行打印(response.content)时的内容。我希望将其组织为
国家/地区:国家/地区名称。 城市:城市名称。 等等...
答案 0 :(得分:1)
将文本格式的响应内容转换为json并使用并获取所需的变量。下面的示例:
import json
response_json = json.loads(response.content)
country_prefix = response_json.get('country_prefix', "")
country_code = response_json.get('country_code', "")
country_name = response_json.get('country_name', "")
city = response_json.get('location', "")
答案 1 :(得分:0)
import json #import json
responseContent = b'{"valid":true,"number":"xxxxxxxxxxx","local_format":"xxxxxxxxxxx","international_format":"xxxxxxxxxxx","country_prefix":"+1","country_code":"US","country_name":"United States of America","location":"Seattle","carrier":"Cellco Partnership (Verizon Wireless)","line_type":"mobile"}' #sample content
data = json.loads(responseContent) #convert bytes to json
for key, value in data.items():
print(key, " : ", value)
结果将是:
valid : True
number : xxxxxxxxxxx
local_format : xxxxxxxxxxx
international_format : xxxxxxxxxxx
country_prefix : +1
country_code : US
country_name : United States of America
location : Seattle
carrier : Cellco Partnership (Verizon Wireless)
line_type : mobile