Selenium is a powerful tool for controlling the web browser through a program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
In this article, we are going to see how to automate the Caloriemama website using selenium. We are just going to post a food picture on caloriemama
API website and return the result it shows on that site.
Before going into code, we need to install selenium for Python.
pip install selenium
Web Drivers
Selenium requires a web driver to interface with the chosen browser.Web drivers is a package to interact with web browser. It interacts with the web browser or a remote web server through a wire protocol which is common to all. You can check out and install the web drivers of your browser choice.
Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads Firefox: https://github.com/mozilla/geckodriver/releases Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/
Modules needed
- selenium: For automating the web browser
- time: For using sleep function because selenium works only when the all the elements of the page is loaded.
We are going to send the picture of the food and get the recognized food result as text. Let’s consider the image of food looks like this –
# food recognition using caloriemama API # selenium example from selenium import webdriver
import time
# create the variable for webdriver browser = webdriver.Firefox(executable_path = '/path/to/geckodriver' )
# it will open browser and # search for the below URL # find class name 'file-upload' upload = browser.find_element_by_class_name( 'file-upload' )
# enter your image file # location here & send image upload.send_keys( "/path/to/food.jpeg" )
time.sleep( 5 )
# return the value by class name get = browser.find_element_by_class_name( 'group-name' )
print (get.text)
# on the website, it will show many # results depend on the accuracy # first result is high accuracy one # if need all the result put it in # loop like below and change # 'find_element_by_class_name' # to 'find_elements_by_class_name' # for got in get: # print(got.text, "\n") # break |
Output:
Pizza