从互联网上读取文件?

时间:2017-04-16 20:13:00

标签: python-3.x windows-7

当我检索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' `

有什么想法吗?

1 个答案:

答案 0 :(得分: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'),这将无效。