2015-11-04 77 views
0

我使用urlretrieve從網站上刮取圖像。除了一個以外,這很有效,而不是非常小的細節。這些文件不可讀。我嘗試了幾個網站,但結果是一樣的。我想知道我是否應該指出它是一個二進制下載,但在文檔中找不到任何提示。搜索了網頁,發現了與請求庫的一些替代方法,但結果相同。 Windows照片查看器,Paint和Gimp都報告該文件已損壞或無法讀取。我很確定我正在犯一些愚蠢的錯誤。任何幫助將不勝感激!urlretrieve似乎損壞圖像文件

def get_images(url, soup): 
    #this makes a list of bs4 element tags 
    print 'URL: ', url 
    n = 0 
    images = [img for img in soup.findAll('img')] 

    #compile our unicode list of image links 
    image_links = [each.get('src') for each in images] 
    for each in image_links: 
     n = n + 1 
     path = urlparse.urlparse(each).path 
     fn = (os.path.split(path)[1]).strip() 
     ext = (os.path.splitext(fn)[1]).strip().lower() 
     if (fn == '' or ext == ''): 
      continue 

     fn = os.path.join ("images", fn) 

#  print 'From: ', url 
     print 'Each> ', each 
#  print 'File< ', fn 
#  avatar = open(fn, 'wb') 
#  avatar.write(requests.get(url).content) 
#  avatar.close() 
     result = urllib.urlretrieve(url, fn) 
     print result 

    return n 

更新

Jephron向我指出了正確的方向,我沒有正確與圖像路徑組合的URL。他的解決方案的工作原理是使用urlparse.urljoin(url, each),正如我最初所做的那樣使用os.path.join,可能會導致突然在Windows系統中的url中出現反斜槓。非常煩人。我添加了相對和絕對url路徑的測試,最終代碼如下所示。

def get_images(url, soup): 
    #this makes a list of bs4 element tags 
    print ' ' 
    print 'URL: ', url 
    n = 0 
    images = [img for img in soup.findAll('img')] 

    #compile our unicode list of image links 
    image_links = [each.get('src') for each in images] 

    for each in image_links: 
     path = urlparse.urlparse(each).path 
     fn = (os.path.split(path)[1]).strip() 
     ext = (os.path.splitext(fn)[1]).strip().lower() 
     if (fn == '' or ext == ''): 
      continue 

     fn = os.path.join ("images", fn) 
     if (not (each.startswith ('http:') or each.startswith('https:'))): 
      image_link = urlparse.urljoin(url, each) 
     else: 
      image_link = each 

     print 'Found: ', fn 

     try: 
      urllib.urlretrieve(image_link, fn) 
      n = n + 1 
     except: 
      continue 

    return n 

但請注意,3/4的.png仍然不可讀。我必須找出原因,但仍可能存在隱藏的障礙。

回答

2

我運行了你的代碼,看看它下載的「圖像」。事實證明,您保存的文件內容實際上是網站的整個HTML。嘗試在文本編輯器中打開它並親自查看。

要解決這個問題,請注意,您傳遞給urlretrieve的參數實際上是您所刮取的網頁的網址。如果您將圖片網址加入網頁網址,您將獲得正確的網址:

def get_images(url, soup): 
    #this makes a list of bs4 element tags 
    print 'URL: ', url 
    n = 0 
    images = [img for img in soup.findAll('img')] 

    #compile our unicode list of image links 
    image_links = [each.get('src') for each in images] 
    for each in image_links: 
     print "maybe an image" 
     print each 
     n = n + 1 
     path = urlparse.urlparse(each).path 
     fn = (os.path.split(path)[1]).strip() 
     ext = (os.path.splitext(fn)[1]).strip().lower() 
     if (fn == '' or ext == ''): 
      continue 

     fn = os.path.join ("images", fn) 

     print 'Each> ', each 

     result = urllib.urlretrieve(os.path.join(url, each), fn) 
     print result 

    return n 
+0

感謝您運行和測試我的代碼的麻煩!它指出我在正確的方向。我用正確的解決方案編輯了我的問題。非常感謝! – Arnold