2016-03-16 47 views
-2

需要從ISS導入數據。 使用代碼拆分urrlib的結果

r= urllib.request.urlopen('http://www.celestrak.com/NORAD/elements/stations.txt') 
x=r.read(1000) 
當我嘗試將數據與

x=x.split("\r\n") 

分裂

我得到的錯誤

raceback (most recent call last): 
File "<pyshell#26>", line 1, in <module> 
x=x.split("\r\n") 
TypeError: a bytes-like object is required, not 'str' 

我該如何解決這個問題?

+0

哪個版本的Python?它看起來像3.x. – jpmc26

回答

-1

響應(x)是bytes實例,因此您需要爲拆分方法提供bytes實例。

x = x.split(b'\r\n')

例如:

>>> res = b'abc\r\ndef' # Note the 'b' at the start, denoting bytes 
>>> res.split('\r\n') 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: a bytes-like object is required, not 'str' 
>>> res.split(b'\r\n') 
[b'abc', b'def'] 

或者你可以在字節解碼爲Unicode,如果你知道自己的編碼,然後調用拆配的字符串:

>>> decoded = res.decode('utf-8') 
>>> print(repr(decoded)) 
'abc\r\ndef' 
>>> decoded.split('\r\n') 
['abc', 'def'] 
+0

如何更改結果 – PowerSoft

+0

你想改變結果的是什麼? – snakecharmerb

+0

如何更改結果[b'ISS(ZARYA)',b'1 25544U 98067A 16076.58963881 .00011510 00000-0 18077-3 0 9992',b'2 2']沒有這個字節實例? – PowerSoft

1

爲什麼不只是使用requests

import requests 

response = requests.get("http://www.celestrak.com/NORAD/elements/stations.txt") 
text = response.text.split("\r\n") 

for t in text: 
    print t