Implement SEO Cron Jobs with Replit and SerpApi Code
Tags: python, replit, api, seo
Published: 2023-03-01 10:22:01

## Intro

This blog post will go over how to use an online IDE called [Replit](https://replit.com/) and how it could be used as a host option to host your SerpApi code to run cron jobs for your SEO, data extraction script, or anything else.

**What is SerpApi?**

SerpApi provides a convenient gateway to access raw data from Google and other search engines through JSON responses, meaning whatever you see in Google or other engines you can see in the response JSON.  

It [has support for 9 languages](https://serpapi.com/integrations/) (and 2 coming soon, Swift and C++). [Playground page to play around and experiment](https://serpapi.com/playground).

**But why Replit?** 

Well, it's simpler from pretty much all sides than other similar tools (such as [pythonanywhere](https://www.pythonanywhere.com/)) and it keeps only getting better and better, at least for now.

**A few words about "Always on" feature**

Please keep in mind that this example requires at least a [Hacker plan](https://replit.com/pricing) that Replit offers, which currently costs $7/month. This plan is required to use of the "Always on" feature. The Replit plan costs $2 more than a [pythonanywhere hacker plan](https://www.pythonanywhere.com/pricing/), I think it's worth it.

## Setting up Replit account and Repl

First, make sure you've registered an account, and then choose a Hacker plan:

![image](https://user-images.githubusercontent.com/78694043/222042175-b660925c-fa5f-45ff-be65-4f3c75c36301.png)

Next, we need to create a repl where all code will be added:

![image](https://user-images.githubusercontent.com/78694043/222064726-6f5ee68e-cede-484a-b6b9-4df6a46252f4.png)

Choose Python as a Template, name your repl however you like, make it public or private, and create the repl:

![image](https://user-images.githubusercontent.com/78694043/222042537-81dacd22-6d2b-4f62-aa3d-12f456236153.png)

After the repl has been created, here are the main things we'll be touching, the same as in your IDE or text editor pretty much:

![image](https://user-images.githubusercontent.com/78694043/222043213-36bf88b3-47b1-4ed2-b0fa-47dacc058570.png)


## Install Packages

Now to the code itself. Add [`google-search-results`](https://github.com/serpapi/google-search-results-python) under the "Packages" tool and install it:

![image](https://user-images.githubusercontent.com/78694043/222043562-ae0d5869-5c28-45ea-ba9b-65d057189b17.png)


Add a [`schedule`](https://github.com/dbader/schedule) package that will do a Cron job:

![image](https://user-images.githubusercontent.com/78694043/222043915-41dc7c88-da93-4f0f-a151-f4122e159c6f.png)


## Code

Here's a very simple example code that runs every 5 seconds until N time and extracts the position of the target website.

[Have a look at how the following example runs on Replit](https://replit.com/@DimitryZub1/Host-SerpApi-code-on-Replit?v=1), in case you want (you need to change `os.getenv("API_KEY")` to [your SerpApi key](https://serpapi.com/manage-api-key)). 

```python
from serpapi import GoogleSearch
import os
import time
from datetime import datetime, time as datetime_time
import schedule


def job():
    TARGET_KEYWORD = 'coffee'
    TARGET_WEBSITE = 'healthline.com'
    QUERY = 'coffee tips'

    params = {
        "api_key": os.getenv("API_KEY"),             # your serpapi api key, https://serpapi.com/manage-api-key
        "engine": "google",                          # serpapi pareser engine
        "location": "Austin, Texas, United States",  # location of the search
        "q": QUERY,                                  # search query
        "gl": "us",                                  # country of the search, https://serpapi.com/google-countries
        "hl": "en",                                  # language of the search, https://serpapi.com/google-languages 
        "num": 100                                   # 100 results
    }

        search = GoogleSearch(params)
        results = search.get_dict()
        
        matched_results = []
        
        for result in results["organic_results"]:
            if TARGET_KEYWORD in result["title"].lower() and TARGET_WEBSITE in result["link"]:
                matched_results.append({
                    "position": result["position"],
                    "match_title": result["title"],
                    "match_link": result["link"]
                })
                
        print(datetime.now().strftime("%H:%M"))
        print(matched_results)
    
if __name__ == "__main__":
    scheduled_off_time = datetime_time(6, 11) # 6 hours, 11 minutes. Repl server local time
    schedule.every(5).seconds.until(scheduled_off_time).do(job)

    while True:
        schedule.run_pending()
        print("job pending ⌛")
        time.sleep(4)
        
        current_time = datetime.now().time()
        
        if current_time > scheduled_off_time:
            schedule.clear()
            print("Done ✅")
            break
```

<details>
<summary>Full execution output</summary>

```
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
https://serpapi.com/search
06:01
[{'position': 75, 'match_title': '8 Ways to Make Your Coffee Super Healthy - Healthline', 'match_link': 'https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy'}]
job pending ⌛
job pending ⌛
job pending ⌛
Done ✅
```
</details>

Returned result:

```json
[
   {
      "position":75,
      "match_title":"8 Ways to Make Your Coffee Super Healthy - Healthline",
      "match_link":"https://www.healthline.com/nutrition/8-ways-to-make-your-coffee-super-healthy"
   }
]
```


The one thing I want to emphasize is that make sure you see what the current time at the repl server is by running the command below. 

This is to make sure you see what the server's local time is as it might be different from your local one.

```python
from datetime import datetime
datetime.now().strftime("%H:%M:%S") # or without %S, %M

# 05:35:02
```

## Setting up "Always on" feature

In addition to enabling the "Always on" feature, you can also enable "Boost repl" if you need more RAM, CPU, and storage:

![enable-always-on-replit-feature](https://user-images.githubusercontent.com/78694043/222059812-13b60e91-b47e-4364-9cfe-d99df18b9a31.gif) 

Yay 🎉 Now your script will be always active and run until a certain time 🙂

With this approach, you can add tools such as Google Cloud Storage to extract the data and immediately upload it to the cloud bucket, and a lot other things.
____

<p style="text-align: center;">Join us on <a href="https://twitter.com/serp_api">Twitter</a> | <a href="https://www.youtube.com/channel/UCUgIHlYBOD3yA3yDIRhg_mg">YouTube</a></p>

<p style="text-align: center;">Add a  <a href="https://github.com/serpapi/public-roadmap/issues">Feature Request</a>💫 or a <a href="https://github.com/serpapi/public-roadmap/issues">Bug</a>🐞</p>