2017-04-16 118 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')这是行不通的。