[英]Python 2.7 download images
I'm using python 2.7 and pycharm is my editor. 我正在使用python 2.7而pycharm是我的编辑器。 What i'm trying to do is have python go to a site and download an image from that site and save it to my directory.
我想要做的是让python进入一个站点并从该站点下载图像并将其保存到我的目录中。 Currently I have no errors but i don't think its downloading because the file is not showing in my directory.
目前我没有错误,但我不认为它的下载,因为该文件没有显示在我的目录中。
import random
import urllib2
def download_web_image(url):
name = random.randrange(1,1000)
full_name = str(name) + ".jpg"
urllib2.Request(url, full_name)
download_web_image("www.example.com/page1/picture.jpg")
This will do the trick. 这样就可以了。 The rest can stay the same, just edit your function to include the two lines I have added.
其余的可以保持不变,只需编辑你的功能,包括我添加的两行。
def download_web_image(url):
name = random.randrange(1,1000)
full_name = str(name) + ".jpg"
request = urllib2.Request(url)
img = urllib2.urlopen(request).read()
with open (full_name, 'w') as f: f.write(img)
Edit 1: 编辑1:
Exact code as requested in comments. 评论中要求的确切代码。
import urllib2
def download_web_image(url):
request = urllib2.Request(url)
img = urllib2.urlopen(request).read()
with open ('test.jpg', 'w') as f: f.write(img)
download_web_image("http://upload.wikimedia.org/wikipedia/commons/8/8c/JPEG_example_JPG_RIP_025.jpg")
You are simply creating a Request
but you are not downloading the image. 您只是创建一个
Request
但您没有下载图像。 Try the following instead: 请尝试以下方法:
urllib.urlretrieve(url, os.path.join(os.getcwd(), full_name)) # download and save image
Or try the requests library: 或者尝试请求库:
import requests
image = requests.get("www.example.com/page1/picture.jpg")
with open('picture.jpg', 'wb') as f:
f.write(image.content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.