【问题标题】:How do I parse every html file in a directory for images?如何解析图像目录中的每个 html 文件?
【发布时间】:2012-03-25 09:44:51
【问题描述】:

我有一个充满 html 文件的目录,每个文件中都有一个牛皮癣患者的临床图像。我想打开每个文件,找到图片,然后保存在同一个目录中。

import os, os.path
import Image
from BeautifulSoup import BeautifulSoup as bs

path = 'C:\Users\gokalraina\Desktop\derm images'

for root, dirs, files in path:
    for f in files:
        soup = bs(f)
        for image in soup.findAll("img"):
            print "Image: %(src)s" % image
            im = Image.open(image)
            im.save(path+image["src"], "JPEG")

我收到此错误:

 Traceback (most recent call last):
   File "C:\Users\gokalraina\Desktop\modfile.py", line 7, in <module>
     for root, dirs, files in path:
 ValueError: need more than 1 value to unpack

即使在谷歌上搜索错误之后,我也不知道出了什么问题,或者我是否正确地执行了此操作。请记住,我是 python 新手。

编辑:对程序进行建议的更改后,我仍然收到错误:

  Traceback (most recent call last):
  File "C:\Users\gokalraina\Desktop\modfile.py", line 25, in <module>
    im = Image.open(image)
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 1956, in open
    prefix = fp.read(16)
 TypeError: 'NoneType' object is not callable

这是修改后的代码(感谢 nightcracker)

 import os, os.path
 import Image
 from BeautifulSoup import BeautifulSoup as bs

 path = 'C:\Users\gokalraina\Desktop\derm images'

 for root, dirs, files in os.walk(path):
    for f in files:
       soup = bs(open(os.path.join(root, f)).read())
       for image in soup.findAll("img"):
          print "Image: %(src)s" % image
          im = Image.open(image)
          im.save(path+image["src"], "JPEG")

【问题讨论】:

  • modfile.py 是您发布的来源吗?第 7 行似乎是一个空行,所以我猜不是。您需要将modfile.py 添加到您的帖子中。
  • 是的,modfile.py 是贴出的代码。

标签: python image jpeg beautifulsoup


【解决方案1】:

你需要改变这一行:

for root, dirs, files in path:

for root, dirs, files in os.walk(path):

还要注意files 是文件名称,而不是对象,所以这将是您的固定代码:

import os, os.path
import Image
from BeautifulSoup import BeautifulSoup as bs

path = 'C:\Users\gokalraina\Desktop\derm images'

for root, dirs, files in os.walk(path):
    for f in files:
        soup = bs(open(os.path.join(root, f)).read())
        for image in soup.findAll("img"):
            print "Image: %(src)s" % image
            im = Image.open(image)
            im.save(path+image["src"], "JPEG")

【讨论】:

  • 感谢您的快速回复。我在程序中更改了那行代码,但它仍然无法按预期工作 - 控制台上没有输出,目录中也没有任何新文件。是不是还有什么做错了?
【解决方案2】:
for root, dirs, files in path:

path 这里是一个字符串。每个元素只有一个字符,您不能将单个字符解压缩为三个变量。因此出现错误消息:您需要多个值才能解压。

你可能想要:

for root, dirs, files in os.walk(path):

【讨论】:

    【解决方案3】:

    您需要使用os.walk(path): 提供一个有意义的列表,提供一个字符串是一个单一的东西,它需要一个东西的列表。

    遍历文件系统的惯用方式是使用os.walk()

    for root, dirs, files in os.walk(path):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多