2014-04-24 38 views
5

我有一個應用程序,基本上是存儲在我的本地驅動器上的圖像數據庫。有時我需要找到更高分辨率的版本或圖像的網絡來源,Google的reverse image search非常適合。谷歌逆向圖像搜索使用POST請求

不幸的是,谷歌沒有它的API,所以我不得不找出一種手動的方法。現在我使用硒,但顯然有很多開銷。我想要一個簡單的解決方案,使用urllib2或類似的東西 - 發送POST請求,獲取搜索URL,然後我可以將該URL傳遞給webbrowser.open(url)以將其加載到我已打開的系統瀏覽器中。

這是我現在使用什麼:

gotUrl = QtCore.pyqtSignal(str) 
filePath = "/mnt/Images/test.png" 

browser = webdriver.Firefox() 
browser.get('http://www.google.hr/imghp') 

# Click "Search by image" icon 
elem = browser.find_element_by_class_name('gsst_a') 
elem.click() 

# Switch from "Paste image URL" to "Upload an image" 
browser.execute_script("google.qb.ti(true);return false") 

# Set the path of the local file and submit 
elem = browser.find_element_by_id("qbfile") 
elem.send_keys(filePath) 

# Get the resulting URL and make sure it's displayed in English 
browser.get(browser.current_url+"&hl=en") 
try: 
    # If there are multiple image sizes, we want the URL for the "All sizes" page 
    elem = browser.find_element_by_link_text("All sizes") 
    elem.click() 
    gotUrl.emit(browser.current_url) 
except: 
    gotUrl.emit(browser.current_url) 
browser.quit() 
+0

如果您是商業用途,TinEye是一個不錯的選擇。如果您可以將它們上傳到www.google.com/searchbyimage? image_url = IMAGE_URL這個網址,那將會很有用。 – Others

回答

8

,如果你很高興安裝requests module這是很容易做到。反向圖片搜索工作流程目前包含一個POST請求,其中包含一個多部分主體到一個上傳URL,其響應是重定向到實際結果頁面。

import requests 

filePath = '/mnt/Images/test.png' 
searchUrl = 'http://www.google.hr/searchbyimage/upload' 
multipart = {'encoded_image': (filePath, open(filePath, 'rb')), 'image_content': ''} 
response = requests.post(searchUrl, files=multipart, allow_redirects=False) 
fetchUrl = response.headers['Location'] 
webbrowser.open(fetchUrl) 

當然,請記住,Google可能決定隨時更改此工作流程!

+1

在這個示例代碼中錯過了另外一個:'import webbrowser' –

+0

從上面的答案返回的'fetchUrl'實際上是模糊匹配生成的圖像的指紋。 – Tengerye