将使用regex在网站上找到的所有图像文件下载到python中我电脑中的指定目录中



我在这里有一个代码,它通过查找regex的文件扩展名来查找所有使用regex的图像文件。现在我要做的是将它保存到计算机上的指定路径,并保留其原始文件名。我当前的代码找到了图像,因为我通过打印"源"进行了测试,但没有将其保存到指定的目录中——也许任何人都可以帮助我调整代码。

提前谢谢。

这是我的代码:

import urllib,re,os
_in = raw_input('< Press enter to download images from first page >')
if not os.path.exists('FailImages'): # Directory that I want to save the image to
        os.mkdir('FailImages') # If no directory create it
source = urllib.urlopen('http://www.samplewebpage.com/index.html').read()
imgs = re.findall('w+.jpg',source) # regex finds files with .jpg extension

#这一点需要调整

for img in imgs:
        filename = 'src="'+ img.split('/')[0]
        if not os.path.exists(filename):
                urllib.urlretrieve(img,filename)

这应该会让你开始。它不处理是否是外部链接,但它会抓取本地图像,

可选

  1. 来自的安装依赖项请求http://requests.readthedocs.org/en/latest/
  2. 从命令行执行:
  3. $ sudo easy_install requests

如果使用请求,取消注释3行f.____#comment去掉最后一行urllib.urlretrieve

import urllib2,re,os
#import requests
folder = "FailImages"
if not os.path.exists(folder): # Directory that I want to save the image to
    os.mkdir(folder) # If no directory create it
url = "http://www.google.ca"
source = urllib2.urlopen(url).read()
imgs = re.findall(r'(https?:/)?(/?[w_-&%?./]*?).(jpg|png|gif)',source, re.M) # regex finds files with .jpg extension

for img in imgs:
    remote = url + img[1] + "." + img[2];
    filename = folder + "/" + img[1].split('/')[-1] + "." + img[2]
    print "Copying from " + remote + " to " + filename
    if not os.path.exists(filename):
        f = open(filename, 'wb')
        f.write(urllib2.urlopen(remote).read())
        #f.write(requests.get(remote).content)
        f.close()

注意:请求的效果要好得多,可以确保发送正确的头,urllib可能在很多时候都不起作用。

最新更新