Recently, someone from a local freelancing platform asked me to write a program to click ads for a given search query on Google. I sent him a sample but he decided not to buy it, so I decided to publish it here.
It uses the Tor network to change the IP address and Selenium with Python bindings for browser automation.
How to Setup Environment and Tor
You can follow the steps manually from this gist to set up Tor or use the following script to set up both virtual environment and Tor.
You should see the following output at the end of the run.
...
Enabling control port...
Setting hashed Tor password...
Starting Tor service...
::::: Setup Completed :::::Run the following commands to start
source env/bin/activate
python ad_clicker.py -q <search keywords>
Since your environment and Tor setup is ready at this point, we can continue with the implementation.
How to Implement the Ad Clicker Automation
After setting up Tor, it is easy to change your IP within Python code using the stem package.
The script requires a query parameter with the -q option. If you used the ad_clicker_setup.sh script, the Tor authentication password will be received from the TOR_PWD environment variable. Otherwise, the user will be asked to type the password determined at the setup phase.
After IP is changed, a search on Google will be initiated for the given query. If there are ads in the results, they will be clicked in order.
The SearchController class is the actual module that does the work. It starts the search and performs clicks for ads found.
The search_for_ads method first locates the search box and enters the search query. After results loaded, the _get_ad_links method locates all ads under the element with id tads, and found ads are returned.
After ads are found, the click_ads method opens them in a different tab by sending Control and left mouse key to the ad link element.
After clicking all the ads, the end_search method closes the browser.