Hello Arsenic¶
This tutorial will show you how to install arsenic and write a simple script that will use Firefox and Google Images to search for pictures of cats.
Prerequisites¶
This tutorial assumes you already have Python 3.6 and Firefox installed.
You will also need to install geckodriver. Download the latest release for your
operating system from the releases page. Extract the binary executable from
the archive and place it in the current directory. On OS X or Linux you might
need to mark it as an executable using chmod +x geckodriver
in your terminal.
Creating a virtual env¶
We will create a virtual env to install arsenic:
python3.6 -m venv env
Let’s make sure that pip
is up to date:
env/bin/pip install --upgrade pip
Let’s install arsenic:
env/bin/pip install --pre arsenic
Writing the script¶
In your favourite text editor, create a file named cats.py
and insert the
following code:
import asyncio
import sys
from arsenic import get_session, keys, browsers, services
if sys.platform.startswith('win'):
GECKODRIVER = './geckodriver.exe'
else:
GECKODRIVER = './geckodriver'
async def hello_world():
service = services.Geckodriver(binary=GECKODRIVER)
browser = browsers.Firefox()
async with get_session(service, browser) as session:
await session.get('https://images.google.com/')
search_box = await session.wait_for_element(5, 'input[name=q]')
await search_box.send_keys('Cats')
await search_box.send_keys(keys.ENTER)
await asyncio.sleep(10)
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(hello_world())
if __name__ == '__main__':
main()
Save it and in the terminal, run python cats.py
. You should see an instance
of Firefox starting, navigating to https://images.google.com
and entering
Cats
in the search box, then submitting the search. The browser will then
wait for 10 seconds for you to look at the cats before exiting.