2012-10-17 26 views
5

我的代碼只返回一個空字符串,我不知道爲什麼。Python中的圖像抓取程序無法按預期運行

import urllib2 

def getImage(url): 
    page = urllib2.urlopen(url) 
    page = page.read() #Gives HTML to parse 

    start = page.find('<a img=') 
    end = page.find('>', start) 

    img = page[start:end] 

return img 

它只會返回它找到的第一個圖像,所以它不是一個很好的圖像刮板;那說,我現在的主要目標就是能夠找到一張圖片。我無法。

回答

0

以這種方式提取圖像信息不是一個好主意。有severaly更好的選擇,這取決於你的知識和你的動機學習新的東西:

+0

知道如何使用正則表達式是有用的技術,但它不是爲網絡以任何方式刮「更好的選擇」。 – root

2

您應該使用這個庫中有幾個在那裏,而是通過改變你向我們展示了代碼回答你的問題......

你的問題是,你正在努力尋找圖片,但圖像不使用<a ...>標籤。他們使用<img ...>標籤。這裏有一個例子:

<img src="smiley.gif" alt="Smiley face" height="42" width="42"> 

你應該做的是你的start = page.find('<a img=')線更改爲start = page.find('<img ')像這樣:

def getImage(url): 
    page = urllib2.urlopen(url) 
    page = page.read() #Gives HTML to parse 

    start = page.find('<img ') 
    end = page.find('>', start) 

    img = page[start:end+1] 
    return img 
+0

我剛剛在http://yahoo.com上嘗試了我建議的'getImage'函數,並得到了這個結果:'' – bohney

2

考慮使用BeautifulSoup解析您的HTML:

from BeautifulSoup import BeautifulSoup 
import urllib 
url = 'http://www.google.com' 
html = urllib.urlopen(url).read() 
soup = BeautifulSoup(html) 
for img in soup.findAll('img'): 
    print img['src'] 
0

一些指令這可能是有幫助的:

  1. 使用谷歌瀏覽器。將鼠標放在圖像上並右鍵單擊。選擇「檢查元素」。這將打開一個部分,您可以在該圖像附近看到html。

  2. 用美麗的湯解析HTML:

    from BeautifulSoup import BeautifulSoup 
    
    request = urllib2.Request(url) 
    response = urllib2.urlopen(request) 
    html = response.read() 
    soap = BeautifulSoap(html) 
    imgs = soup.findAll("img") 
    items = [] 
    for img in imgs: 
        print img['src'] #print the image location 
        items.append(img['src']) #store the locations for downloading later 
    
相關問題