Skip to content

Instantly share code, notes, and snippets.

@zeratax
Last active December 30, 2022 09:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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")
@HyeAnn-Lee
Copy link

line 20 seems not working anymore ;( https://stackoverflow.com/a/60122613/14257620

@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