【问题标题】:Download all the image files found using regex on a website to a specified directory in my computer in python将网站上使用正则表达式找到的所有图像文件下载到我计算机中python的指定目录
【发布时间】:2013-12-22 00:45:14
【问题描述】:

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

提前致谢。

这是我的代码:

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)

【问题讨论】:

  • 我怀疑您将面临比简单地将所有图像文件转储到文件夹中更具挑战性的任务。仅当图像的名称不同时,这才有效。您最好的选择是捕获图像的相对路径(对于本地图像)并在本地重新创建文件夹结构;对于外部图像,您可能希望创建类似的结构,但包含在 www.externalimage.com 之类的文件夹中。
  • 页面上的图片是否具有相同的文件名并不重要
  • 即使有些被覆盖? (1.jpg 会覆盖 1.jpg)?
  • 是的,我只需要一个简单的代码即可将图像从网站下载/保存到我的文件夹。代码不一定要健壮。

标签: python regex image url download


【解决方案1】:

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

可选

  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()

注意Requests 工作得更好,并确保发送正确的标头,urllib 可能在很多时候无法工作。

【讨论】:

  • 感谢您的代码。但我必须在 Python 上使用标准模块。所以没有安装模块。
  • 我几乎可以正常工作了。我所做的是取消注释 f.close 和 f=open 但留下 f.write 注释,因为它给了我错误'未定义的请求'。它使用原始文件名获取并保存图像,这是我想要的但不包含任何字节,只是文件夹中的一个文件。有什么建议?提前致谢
  • 这就是使用 urlretrieve 会遇到的问题 - 它没有传递正确的标头。如果我的电源还没有熄灭,我会在 f.write 中使用 url 检索对其进行编辑。如果它再次出现,我会更新。如果可以,请尝试自己,将 url 检索包装在 f.write()
  • 我现在可以正常工作了。它只下载文件的部分大小,就像其中一张图像一样,它只下载 246 字节而不是 43 KB。你觉得我应该怎么做?
  • 知道了- 修复它以使用 urllib2 (为什么我一开始没有使用?)
猜你喜欢
  • 1970-01-01
  • 2018-12-06
  • 1970-01-01
  • 2014-10-28
  • 2011-06-05
  • 2018-05-30
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多