2013-11-03 26 views
2

我寫了下面的Python代碼從網站www.style.comPython的BeautifulSoup網頁圖像抓取器IO錯誤:[錯誤2]沒有這樣的文件或目錄

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] No such file or directory: '/images/homepage-2013-october/header/logo.png'

如何解決?

也可以遞歸地找到網站中的所有圖像?我的意思是其他圖像不在主頁上。

謝謝!

+0

你提到的錯誤是無處代碼。 – aIKid

+0

你應該發佈由python –

回答

0
  1. 當您嘗試檢索URL時,您正在使用沒有域的相對路徑。
  2. 某些圖像是基於javascript的,你會得到相對路徑爲javascript:void(0);,你永遠不會得到該頁面。我添加了try except以解決該錯誤。或者,您可以巧妙地檢測URL是否以jpg/gif/png結尾。我會爲你工作:)
  3. 順便說一句,並非所有的圖像都包含在URL中,一些圖片,美麗的一個,使用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() 
+0

給出的完整回溯錯誤,它會產生錯誤:InvalidURL:nonnumeric port:'void(0);' – randomp

+0

@randomp我暫時刪除了你的OOP部分,因爲它在開始時很混亂。也許你可以嘗試一下,看看這些代碼是否有效。如果是這樣,你可以重新使用OOP。 –

+0

當然。非常感謝! – randomp

相關問題