Skip to content

Instantly share code, notes, and snippets.

@zeratax
Last active December 30, 2022 09:53
Show Gist options
  • Save zeratax/a0719af17fdf8d338f8fdd6601f90a36 to your computer and use it in GitHub Desktop.
Save zeratax/a0719af17fdf8d338f8fdd6601f90a36 to your computer and use it in GitHub Desktop.
get first result from google image search
from bs4 import BeautifulSoup
import requests
def get_google_img(query):
"""
gets a link to the first google image search result
:param query: search query string
:result: url string to first result
"""
url = "https://www.google.com/search?q=" + str(query) + "&source=lnms&tbm=isch"
headers={'User-Agent':"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"}
html = requests.get(url, headers=headers).text
soup = BeautifulSoup(html, 'html.parser')
image = soup.find("img",{"class":"t0fcAb"})
if not image:
return
return image['src']
if __name__ == '__main__':
query = input("search term\n")
print(get_google_img(query) or "no image found")
@zeratax
Copy link
Author

zeratax commented May 14, 2021

@happy1004ann here I updated it, but I don't intend to maintain this. seems like google is heavily fuzzing their class names so it's probably not going to work for long

@tsuiwilliam
Copy link

https://keywordimage.com/ is a free (by donation) online service that does this without code/hosting.

replace "beanies" in https://keywordimage.com/image.php?q=Beanies with your keywords and you'll get the first image result from google as the output

Consider donating if you are using more than 50 requests http://buymeacoffee.com/keywordimage

@p0c07o
Copy link

p0c07o commented Dec 30, 2022

@tsuiwilliam
I tried using your Keywordimage service. It works when executed in a browser, but fails when run thru Google App Script:
image
Any idea why?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment