2017-04-16 67 views
-1

當我檢索一個URL(通過發送到random.cat的請求)像這樣:從互聯網上讀取文件?

print('Importing REQUESTS') 
import requests 
import json 
import urllib 
response = (requests.get("http://random.cat/meow")) 
response = str(response.content) 
print(response) 
response = response.replace("b'","") 
response = response.replace("'","") 
response = response.replace("\\","") 
print(response) 
data = json.loads(response) 
print (data["file"])` 

然後我嘗試使用打開它:

with open(line, 'rb') as f: 
    print("work")` 

我得到這個錯誤:

Traceback (most recent call last): 
    File "G:/catimages.py", line 21, in <module> 
    with open(line, 'rb') as f: 
OSError: [Errno 22] Invalid argument: 'http://random.cat/i/8Vilp.jpg' ` 

任何想法?

回答

0

open無法直接打開網址。您需要先使用請求下載文件。見How do I download a file over HTTP using Python?

編輯:要清楚,你所提供的錯誤信息表明,line'http://random.cat/i/8Vilp.jpg',所以你嘗試調用open('http://random.cat/i/8Vilp.jpg', 'rb')這是行不通的。