【问题标题】:Python BeautifulSoup web image crawler IOError: [Errno 2] No such file or directoryPython BeautifulSoup 网络图片爬虫 IOError: [Errno 2] No such file or directory
【发布时间】:2013-11-14 08:25:19
【问题描述】:

我编写了以下 Python 代码来抓取网站 www.style.com 中的图像

 import urllib2, urllib, random, threading
 from bs4 import BeautifulSoup
 import sys
 reload(sys)
 sys.setdefaultencoding('utf-8')

 class Images(threading.Thread):
   def __init__(self, lock, src):
     threading.Thread.__init__(self)
     self.src = src
     self.lock = lock

   def run(self):
     self.lock.acquire()
     urllib.urlretrieve(self.src,'./img/'+str(random.choice(range(9999))))
     print self.src+'get'
     self.lock.release()

 def imgGreb():
   lock = threading.Lock()
   site_url = "http://www.style.com"
   html = urllib2.urlopen(site_url).read()
   soup = BeautifulSoup(html)
   img=soup.findAll(['img'])
   for i in img:
     print i.get('src')
     Images(lock, i.get('src')).start()

 if __name__ == '__main__':
   imgGreb()

但是我收到了这个错误:

IOError: [Errno 2] 没有这样的文件或目录:'/images/homepage-2013-october/header/logo.png'

如何解决?

这也可以递归查找网站中的所有图像吗?我的意思是主页上没有的其他图片。

谢谢!

【问题讨论】:

  • 你提到的错误不在代码中。
  • 你应该发布python给出的完整回溯错误

标签: python python-2.7 beautifulsoup web-crawler


【解决方案1】:
  1. 当您尝试检索 URL 时,您使用的是不带域的相对路径。
  2. 有些图像是基于 javascript 的,您将获得相对路径为 javascript:void(0);,而您将永远无法获得该页面。我添加了try except 来解决这个错误。或者您可以巧妙地检测 URL 是否以 jpg/gif/png 结尾。我会为你工作的:)
  3. 顺便说一句,并非所有图片都包含在 URL 中,有些图片 Beautiful One 是使用 Javascript 调用的,我们只能使用 urllibbeautifulsoup 来做些什么。如果你真的想挑战自己,也许你可以尝试学习Selenium,这是一个更强大的工具。

直接试试下面的代码:

import urllib2
from bs4 import BeautifulSoup
import sys
from urllib import urlretrieve
reload(sys)


def imgGreb():
    site_url = "http://www.style.com"
    html = urllib2.urlopen(site_url).read()
    soup = BeautifulSoup(html)
    img=soup.findAll(['img'])
    for i in img:
        try:
            # built the complete URL using the domain and relative url you scraped
            url = site_url + i.get('src')
            # get the file name 
            name = "result_" + url.split('/')[-1] 
            # detect if that is a type of pictures you want
            type = name.split('.')[-1]
            if type in ['jpg', 'png', 'gif']:
                # if so, retrieve the pictures
                urlretrieve(url, name)
        except:
            pass

if __name__ == '__main__':
    imgGreb()

【讨论】:

  • 会产生错误:InvalidURL: nonnumeric port: 'void(0);'
  • @randomp 我暂时删除了您的 OOP 部分,因为它一开始就令人困惑。也许您可以尝试一下,看看这些代码是否有效。如果是这样,您可以使用 OOP 重新实现。
  • @randomp 它对你有用吗?如果是这样,请将此问题标记为已回答,这将对其他人有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-07-23
  • 2018-06-10
相关资源
最近更新 更多