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")
@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