A Google Reverse Images API használata a SerpApi-tól

  • „Mi az a Google Reverse Images”
  • "Egyszerű Hello World"
  • "Részletes kód"
  • "Előfeltételek"
  • "Kód magyarázata"
  • „Miért használjunk API-t?”
  • "Linkek"

Mi az a Google Reverse Images

Egyszerűen fogalmazva, segít gyorsan felfedezni a vizuálisan hasonló képeket az internetről. A felhasználó feltölthet egy fényképet az asztali számítógépéről/mobiltelefonjáról, vagy beillesztheti egy fénykép URL-jét, és szinte azonnal megjeleníti Önnek a más webhelyeken használt kapcsolódó képeket, valamint ugyanannak a fényképnek a különböző méretét.

Például készíthet (beilleszthet URL-t) egy fotót egy minecraft párnáról, és használhatja információk vagy hasonló képek keresésére.

Az eredmények a következőket tartalmazhatják:

  • Keresési eredmények a képen lévő objektumokra.
  • Hasonló képek.
  • A képet vagy hasonló képet tartalmazó webhelyek.

Ebben a blogbejegyzésben bemutatjuk, hogyan használhatja a SerpApi képességét a fordított képek eredményeiből származó adatok elemzésére. Böngészőautomatizálás nélkül csináljuk, ami sokkal gyorsabb.

Példa azokra a találatokra, amelyeket egy adott kép alapján ad vissza a Google:

A tipikus fordított képfolyamat:

Egyszerű Hello World

from serpapi import GoogleSearch
import os, json
image_url = "https://user-images.githubusercontent.com/81998012/182214192-59dfb3fe-522c-4979-bb42-9f8091dfd9d6.jpg"
params = {
    # https://docs.python.org/3/library/os.html#os.getenv
    "api_key": os.getenv("API_KEY")     # your serpapi api key
    "engine": "google_reverse_image",   # SerpApi search engine
    "image_url": image_url,             # image URL to perform a reverse search
    "hl": "en",                         # language of the search
    "gl": "us"                          # country of the search
    # other parameters
}
search = GoogleSearch(params)           # where data extraction happens on the SerpApi backend
results = search.get_dict()             # JSON -> Python dictionary
# ["image_results"] is basically a Google organic results
print(json.dumps(results["image_results"], indent=4, ensure_ascii=False))

Részletes kód

from serpapi import GoogleSearch
import os, json
image_urls = [
    "https://user-images.githubusercontent.com/81998012/182214192-59dfb3fe-522c-4979-bb42-9f8091dfd9d6.jpg",
    "https://user-images.githubusercontent.com/81998012/182025185-27df7683-24d5-4747-904b-9f3a6045705b.jpg",
    "https://user-images.githubusercontent.com/81998012/182025195-fec95c5c-aee1-448b-9165-ce9dc1b77a56.jpg",
    "https://user-images.githubusercontent.com/81998012/182027073-4b09a0b7-ec55-415f-bcb0-7a457e87c0b4.jpg",
    "https://user-images.githubusercontent.com/81998012/182025215-ce739965-5c4f-4735-8581-566e03b609f2.jpg",    
]

def main():
    google_reverse_image_data = {}
    for index, image_url in enumerate(image_urls, start=1):
        google_reverse_image_data[f"results for image {index}"] = {}
        params = {
            # https://docs.python.org/3/library/os.html#os.getenv
            "api_key": os.getenv("API_KEY")     # your serpapi api key
            "engine": "google_reverse_image",   # SerpApi search engine
            "image_url": image_url,             # image URL to perform a reverse search
            "location": "Dallas",               # location from where search comes from
            "hl": "en",                         # language of the search
            "gl": "us"                          # country of the search
            # other parameters
        }
        
        search = GoogleSearch(params)           # where data extraction happens on the SerpApi backend
        results = search.get_dict()             # JSON -> Python dictionary
        # some queries may not include this information
        if results["knowledge_graph"]:
            knowledge_graph = {}
            
            knowledge_graph["title"] = results["knowledge_graph"]["title"]
            knowledge_graph["description"] = results["knowledge_graph"]["description"]
        
            google_reverse_image_data[f"results for image {index}"]["knowledge_graph"] = knowledge_graph
        # some queries may not include organic results
        if results["image_results"]:
            google_reverse_image_data[f"results for image {index}"]["organic_results"] = []
            
            for result in results["image_results"]:
                image_results = {}
                
                image_results["position"] = result["position"]
                image_results["title"] = result["title"]
                image_results["link"] = result["link"]
                image_results["snippet"] = result["snippet"]
        
                google_reverse_image_data[f"results for image {index}"]["organic_results"].append(image_results)
        # some queries may not include this information
        if results["inline_images"]:
            google_reverse_image_data[f"results for image {index}"]["inline_images"] = []
            
            for result in results["inline_images"]:
                google_reverse_image_data[f"results for image {index}"]["inline_images"].append({
                    "source": result["source"],
                    "thumbnail": result["thumbnail"]
                })
    return google_reverse_image_data

if __name__ == "__main__":
    print(json.dumps(main(), indent=4, ensure_ascii=False))

Előfeltételek

pip install google-search-results

Kód magyarázata

Könyvtárak importálása:

from serpapi import GoogleSearch
import os, json
  • osa környezeti változó (SerpApi API kulcs) értékének visszaadásához.
  • jsona kivont adatok JSON-objektummá konvertálásához.
  • GoogleSearcha Google találatainak lekaparásához és elemzéséhez a SerpApiwebes adattárral.

Ezután list URL-re van szükségünk az adatok kereséséhez (bármi lehet, ami ismételhető):

image_urls = [
    "https://user-images.githubusercontent.com/81998012/182214192-59dfb3fe-522c-4979-bb42-9f8091dfd9d6.jpg",
    "https://user-images.githubusercontent.com/81998012/182025185-27df7683-24d5-4747-904b-9f3a6045705b.jpg",
    "https://user-images.githubusercontent.com/81998012/182025195-fec95c5c-aee1-448b-9165-ce9dc1b77a56.jpg",
    "https://user-images.githubusercontent.com/81998012/182027073-4b09a0b7-ec55-415f-bcb0-7a457e87c0b4.jpg",
    "https://user-images.githubusercontent.com/81998012/182025215-ce739965-5c4f-4735-8581-566e03b609f2.jpg",    
]

Ezután létre kell hoznunk egy main függvényt (nem kötelező), és létre kell hoznunk egy ideiglenes dict-t a kivont adatok tárolására:

def main():
    google_reverse_image_data = {}

A következő lépéshez meg kell ismételnünk az összes image_urls értéket, és át kell adni az értékét a "image_url" params kulcsnak:

for index, image_url in enumerate(image_urls, start=1):
    google_reverse_image_data[f"results for image {index}"] = {}
    params = {
        "engine": "google_reverse_image",   # SerpApi search engine
        "image_url": image_url,             # image URL to perform a reverse search
        "location": "Dallas",               # location from where search comes from
        "hl": "en",                         # language of the search
        "gl": "us",                         # country of the search
        # https://docs.python.org/3/library/os.html#os.getenv
        "api_key": os.getenv("API_KEY"),    # your serpapi api
    }
    
    search = GoogleSearch(params)           # where data extraction happens on the SerpApi backend
    results = search.get_dict()
  • enumerate()számláló hozzáadása egy iterálható elemhez, és visszaadhatja azt. Ebben az esetben ez arra szolgál, hogy pontosabban mutassa meg, hogy mely eredmények melyik képhez tartoznak.

Most ellenőriznünk kell, hogy if minden konkrét adat visszakerül-e hozzánk. Ebben az esetben csak a knowledge_graph, organic_results (image_results) és inline_images jeleket ellenőrizzük:

if results["knowledge_graph"]:
    knowledge_graph = {}
    
    knowledge_graph["title"] = results["knowledge_graph"]["title"]
    knowledge_graph["description"] = results["knowledge_graph"]["description"]
    google_reverse_image_data[f"results for image {index}"]["knowledge_graph"] = knowledge_graph
if results["image_results"]:
    google_reverse_image_data[f"results for image {index}"]["organic_results"] = []
    
    for result in results["image_results"]:
        image_results = {}
        
        image_results["position"] = result["position"]
        image_results["title"] = result["title"]
        image_results["link"] = result["link"]
        image_results["snippet"] = result["snippet"]
        google_reverse_image_data[f"results for image {index}"]["organic_results"].append(image_results)
if results["inline_images"]:
    google_reverse_image_data[f"results for image {index}"]["inline_images"] = []
    
    for result in results["inline_images"]:
        google_reverse_image_data[f"results for image {index}"]["inline_images"].append({
            "source": result["source"],
            "thumbnail": result["thumbnail"]
        })

Most vissza kell adnunk az adatokat:

return google_reverse_image_data

Az utolsó lépés egy Python idióma hozzáadása, hogy megbizonyosodjon arról, hogy "az olvasók ezt a kódot végrehajtható szkriptként értelmezik", és kinyomtatják az adatokat:

if __name__ == "__main__":
    print(json.dumps(main(), indent=4, ensure_ascii=False))

Kimenet:

{
    "results for image 1": {
        "knowledge_graph": {
            "title": "Stairs",
            "description": "Stairs are a structure designed to bridge a large vertical distance by dividing it into smaller vertical distances, called steps. Stairs may be straight, round, or may consist of two or more straight pieces connected at angles. Types of stairs include staircases, ladders, and escalators."
        },
        "organic_results": [
            {
                "position": 1,
                "title": "Stairs - Wikipedia",
                "link": "https://en.wikipedia.org/wiki/Stairs",
                "snippet": "Stairs are a structure designed to bridge a large vertical distance by dividing it into smaller vertical distances, called steps. Stairs may be straight, ..."
            }, ... other organic results
            {
                "position": 4,
                "title": "Foto HD de Claudio Schwarz - Unsplash",
                "link": "https://unsplash.com/es/fotos/ipcsI15th5I",
                "snippet": "Nuevo: Unsplash ahora está disponible en varios idiomas. Puedes volver a cambiar al inglés cuando quieras. Próximamente habrá más idiomas."
            }
        ],
        "inline_images": [
            {
                "source": "https://www.flickr.com/photos/thepiratesgospel/6107309586/",
                "thumbnail": "https://serpapi.com/searches/62e907cb5b54ef5af08d6ff2/images/6886d2b2c5499da05d656e39563b001cc2a1b485150c7a5761ed1190edbccb0f.jpeg"
            }, ... other thumbnails
            {
                "source": "https://en-gb.facebook.com/qualitycarpetsdirect/posts/",
                "thumbnail": "https://serpapi.com/searches/62e907cb5b54ef5af08d6ff2/images/6886d2b2c5499da08e88e75176317a1c08b36d2c2800f2329de12d162eab24e9.jpeg"
            }
        ]
    }, ... other results
    "results for image 5": {
        "knowledge_graph": {
            "title": "Art",
            "description": "Art is a diverse range of human activity, and resulting product, that involves creative or imaginative talent expressive of technical proficiency, beauty, emotional power, or conceptual ideas."
        },
        "organic_results": [
            {
                "position": 1,
                "title": "Art.com | Wall Art: Framed Prints, Canvas Paintings, Posters ...",
                "link": "https://www.art.com/",
                "snippet": "Shop Art.com for the best selection of wall art and photo prints online! Low price guarantee, fast shipping & free returns, and custom framing options ..."
            },
            {
                "position": 2,
                "title": "Art - Wikipedia",
                "link": "https://en.wikipedia.org/wiki/Art",
                "snippet": "Art is a diverse range of human activity, and resulting product, that involves creative or imaginative talent expressive of technical proficiency, beauty, ..."
            }
        ],
        "inline_images": [
            {
                "source": "https://www.leireunzueta.com/journal/tag/summer",
                "thumbnail": "https://serpapi.com/searches/62e907d0e13508b8c60f4c3b/images/6c0c95a05f3c4aa45e83ffe98a6112df67130eb20d484feef2c133f72ab49a3f.jpeg"
            }, ... other thumbnails
            {
                "source": "https://unsplash.com/photos/onMwdrVfMuE",
                "thumbnail": "https://serpapi.com/searches/62e907d0e13508b8c60f4c3b/images/6c0c95a05f3c4aa4deae63325b5a810305c9d32f794fc72c1849753080f116fa.jpeg"
            }
        ]
    }
}

Miért használjunk API-t?

  • Nincs szükség elemző létrehozására és karbantartására a semmiből.
  • A Google blokkjainak megkerülése: oldja meg a CAPTCHA-t vagy oldja meg az IP-blokkokat.
  • Fizessen a proxyért és a CAPTCHA-megoldókért.
  • Nem kell böngészőautomatizálást használnia.

A SerpApi mindent kezel a háttérben, nagyon gyors válaszidővel és böngészőautomatizálás nélkül, ami sokkal gyorsabbá válik.

Az átlag ~2,07 másodperc 20 keresési lekérdezés alapján (a képernyőképen 15 keresési lekérdezés látható):

Linkek

  • "Kód az online IDE-ben"
  • "Google Reverse Image API"

Eredetileg a SerpApi-nál tették közzé: https://serpapi.com/blog/using-google-reverse-images-api/

Csatlakozzon hozzánk a Twitteren | "Youtube"

Adjon hozzá egy "Funkciókérés"💫 vagy egy "Hiba"🐞