在单打印功能中跳转到下一行

时间:2017-12-13 13:04:07

标签: python-3.x

标题可能并不完美。 我正在尝试使用python3中的api创建一个IP查找/跟踪程序,一切看起来都不错,但我不喜欢输出在终端中的打印方式。顺便说一下,我还是蟒蛇新手。

这是我的代码:

#!/usr/bin/python3
from urllib.request import urlopen
content = urlopen("http://api.hackertarget.com/geoip/?q=139.59.19.197")
print(content.read())

我得到的输出:

b'IP Address: 139.59.19.197\nCountry: IN\nState: Karnataka\nCity: Bangalore\nLatitude: 12.983300\nLongitude: 77.583298'

我想要的输出:

IP Address: 139.59.19.197
Country: IN
State: Karnataka
City: Bangalore
Latitude: 12.983300
Longitude: 77.583298

我有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

urllib read方法为您提供原始字符串,而不是文本。 Python表示转义任何不在32-127范围内的字符。

您只需在打印前将收到的数据解码为正确的文字。

当然," easy"方法是天真地选择一个编码,如" utf-8"并使用它。但是,您检索的HTTP数据在某些时候将具有正确的编码 - 在其标题上或在元html标记内。

这就是为什么我们通常会使用外部requests库进行此类操作。

在这种情况下,您似乎正在使用仅具有ASCII字符的Web服务。所以你可以使用" latin1"并冒险有任何mojibake:

#!/usr/bin/python3
from urllib.request import urlopen
content = urlopen("http://api.hackertarget.com/geoip/?q=139.59.19.197")
data = content.read().decode("latin1")
print(data)

如果您还有5分钟的时间,请阅读以下内容: https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/ - 它是从2003年开始的,但今天并不那么重要。