# How to Build an SEO and AI Search Visibility Workflow in Python with Olostep

> Source: <https://dev.to/balapriya/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep-2hgp>
> Published: 2026-11-25 03:30:05+00:00

**Key takeaway:** Olostep's SDK exposes maps, searches, scrapes, crawls, answers and batches calls, and its batch AI parsers return structured answers with citations from ChatGPT, Perplexity, Gemini, Google AI Mode, Google AI Overview and Copilot.

A search visibility team has to answer several questions. What does our site look like to a crawler? Who competes with us for these queries? What are they publishing? And what do AI tools like ChatGPT, Perplexity and Gemini say when someone asks about our category?

Each question needs a different data pull: a list of URLs, a set of search results, the text of a page, a batch of AI answers. Built by hand, each pull is its own script to write, test and maintain.

Olostep is a web data API with an endpoint for each of those pulls:

In addition, its AI search parsers return structured answers and citations from ChatGPT, Perplexity, Gemini, Google AI Mode, Google AI Overview and Copilot.

In this tutorial, you'll learn how to run all of these from one Colab notebook. You'll map a site, find competitors, audit a competitor's page, crawl a blog, pull a competitor profile, scrape a URL list in bulk and track your brand across AI engines. Each step is a short piece of code that builds on the one before it.

You can follow along in [this Colab notebook](https://github.com/balapriyac/python-basics/blob/main/seo-ai-search-workflow-olostep/seo_ai_visibility_workflow_olostep_v1.ipynb)

Let's get started!

`olostep` SDK requires 3.11, docs tested for Python versions 3.11 to 3.13)
Let's start with an overview of the various Olostep endpoints and their equivalent SDK calls:

| Job | Endpoint | SDK call | 
|---|---|---|
| Detect site structure | Maps | `client.maps.create()` | 
| Find competitors | Search | `client.searches.create()` | 
| Retrieve one page | Scrapes | `client.scrapes.create()` | 
| Retrieve a section of a site | Crawls | `client.crawls.create()` | 
| Retrieve a researched fact | Answers | `client.answers.create()` | 
| Collect a known URL list at volume | Batches | `client.batches.create()` | 
| Track prompts across AI engines | Batches with AI parsers | `client.batches.create(parser=...)` | 

Install the SDK first.

```
!pip install -q olostep
```

Next, load your API key. The code checks the `OLOSTEP_API_KEY` environment variable first and falls back to a hidden prompt, so the key never lands in the notebook.

``` python
import os
from getpass import getpass

from olostep import Olostep  # make sure you've installed the Python SDK

# 1. Retrieve the API key
api_key = os.getenv("OLOSTEP_API_KEY")
if not api_key:
    api_key = getpass("Please enter your Olostep API Key: ")
    os.environ["OLOSTEP_API_KEY"] = api_key

# 2. Initialize the client
client = Olostep(api_key=api_key)
```

Then set the values you'll change for your own project.

```
SITE = "https://your-site-here.com"  # your site
BRAND = "Your Brand Here"  # how people write your brand name
BRAND_DOMAIN = "your-site-here.com"  # your bare domain
BLOG_PATH = "/blog/"  # where your site publishes articles
CATEGORY = "your category here"  # the topic you want to rank and be cited for

COMPETITOR = "https://competitor-here.com"  # one competitor to study
```

**Note:** Replace each placeholder with your own value before you run anything:

`SITE`, `BRAND` and `BRAND_DOMAIN` describe your site.`BLOG_PATH` is where your site publishes articles.`CATEGORY` is the topic you want to rank and be cited for.`COMPETITOR` is the competitor you want to study. If you don't have one yet, leave the placeholder for now and update it after Step 3, which searches for competitors in your category.
The sample outputs in this tutorial come from running the notebook on Stripe, with Wise as the competitor. The notebook only reports what Olostep returns, so your results will differ.

Step 5 has two more strings for your competitor's article pages, and it explains how to find them.

A map returns the URLs Olostep finds on a site. For an SEO team, this is the raw material of a content inventory.

```
site_map = client.maps.create(url=SITE)
urls = list(site_map.urls())
print(f"Found {len(urls)} URLs")
```

For the example site, `stripe.com`, this printed:

```
Found 7437 URLs
```

`site_map.urls()` yields each URL as a string, and `list()` collects them. Counting URLs by their first path segment shows where your site's weight sits.

``` python
from collections import Counter
from urllib.parse import urlparse

def section(url):
    first = urlparse(url).path.strip("/").split("/")[0]
    return f"/{first}" if first else "/"

for name, count in Counter(section(u) for u in urls).most_common(10):
    print(f"{count:>5}  {name}")
```

For `stripe.com`, the ten largest sections looked like this:

```
3658  /resources
 1440  /careers
  590  /customers
  399  /legal
  279  /newsroom
  275  /blog
  206  /guides
  170  /sessions
   57  /payment-method
   28  /payments
```

The loop prints your ten largest sections. A section with hundreds of URLs and no internal links pointing to it is worth a look, and so is a section you expected to be large that shows up with a handful. You'll reuse `urls` in Step 7.

Search takes a natural-language query and returns deduplicated links with titles and descriptions. Pass your own domain to `exclude_domains` so you don't find yourself.

```
search = client.searches.create(
    f"best {CATEGORY}",
    limit=10,
    exclude_domains=[BRAND_DOMAIN],
)

for link in search.links:
    print(urlparse(link["url"]).netloc, "|", link["title"])
```

Sample output for the Stripe example:

```
airwallex.com | 5 best online payment processing services of 2026
airwallex.com | 5 best payment processors of 2026
nerdwallet.com | Stripe Review 2026: Features and Pricing - NerdWallet
wise.com | 7 Cheapest Payment Processing Services for Small Businesses - Wise
nerdwallet.com | Best Payment Gateways of 2026 - NerdWallet
www.forbes.com | 7 Best Payment Gateways – Forbes Advisor
learn.g2.com | I Evaluated the 6 Best Payment Processing Software for 2026
techrepublic.com | The 6 Best Payment Processing Providers
nerdwallet.com | 5 Best Payment Processors for Small Business in 2026
forbes.com | 10 Best Credit Card Processing Companies of 2026 – Forbes Advisor
```

Each link is a dictionary with `url`, `title` and `description`. A category query returns listicles and review sites next to direct competitors, so read the list and pick a real one. Each search costs 5 credits, per the [search docs](https://docs.olostep.com/features/search). Wise appears in the sample output. It is a payments company that competes with Stripe, so it is the example competitor in this tutorial. **On your own site, pick a competitor from your results and paste it into `COMPETITOR`.**

You now have your site, its structure and a competitor. The remaining steps work on any competitor, and each one tells you which strings to replace with your own.

**Note**: Before you scrape or crawl a competitor: read their terms of service and `robots.txt`. If either forbids automated access, skip that site and pick another. Collect public pages only, never anything behind a login, and never personal data. Use what you collect for analysis, such as word counts, headings and topics, and don't republish their content. Keep crawls small. You are responsible for how you use what you collect.

A scrape converts one URL into clean markdown. Pull the competitor's homepage and look at how it is organized.

```
page = client.scrapes.create(url_to_scrape=COMPETITOR, formats=["markdown"])
markdown = page.markdown_content

print(f"{len(markdown.split())} words")
for line in markdown.splitlines():
    if line.startswith("#"):
        print(line)
```

This step reads `COMPETITOR` from Step 1. To study a different page, replace `url_to_scrape=COMPETITOR` with any URL you want to audit, such as a competitor's pricing page or a post that ranks for your category.

A scrape handles one page. A crawl starts at a URL and follows links, and `include_urls` limits it to the paths you care about. `max_pages=25` keeps this run small.

Two strings in the code below are yours to replace:

`COMPETITOR_START` is the page where your competitor lists its articles. Open their site, find the blog or resources section, and copy that URL.`COMPETITOR_PATTERN` is the path their article URLs share, ending in `/**`. If the articles live at `/blog/some-post`, the pattern is `/blog/**`.

```
COMPETITOR_START = "https://competitor-here.com/blog/"  # replace with your competitor's article listing page
COMPETITOR_PATTERN = "/blog/**"  # replace with the path their articles share

crawl = client.crawls.create(
    start_url=COMPETITOR_START,
    include_urls=[COMPETITOR_PATTERN],
    max_pages=25,
)
```

`crawl.pages()` waits for the crawl to finish, then yields each page. Retrieve the markdown for each one and count the words.

```
rows = []
for post in crawl.pages():
    content = post.retrieve(["markdown"])
    words = len((content.markdown_content or "").split())
    rows.append((post.url, words))

for url, words in sorted(rows, key=lambda r: r[1], reverse=True)[:10]:
    print(f"{words:>6}  {url}")
```

You now have a ranked list of the competitor's longest posts. The URL slugs show the topics they cover, and the word counts show where they go deep.

Some facts are not on one page: what a company sells, who it targets, how it prices. Answers browses the web for them and returns a result with sources. Pass `json_format` to get named fields back.

```
answer = client.answers.create(
    task=f"What does {COMPETITOR} sell, who is it for, and how is it priced?",
    json_format={"product": "", "audience": "", "pricing": ""},
)
print(answer.json_content["product"])
```

**But what happens when you index into the result?**

**The problem:** the code stops with `TypeError: string indices must be integers, not 'str'`. In the SDK, `answer.json_content` is a JSON string, so text keys don't work on it.

**The solution:** parse it with `json.loads`.

``` python
import json

profile = json.loads(answer.json_content)
print(profile)
print(answer.sources)
```

`profile` is now a dictionary with your three fields, and `answer.sources` lists the URLs the answer came from. Fields Olostep can't verify come back as `NOT_FOUND`. The task string uses `COMPETITOR`, so changing that value in Step 1 profiles a different company.

An answer costs 20 credits, per the [answers docs](https://docs.olostep.com/features/answers). I'd use it for the few facts you can't scrape, and use Step 4 for anything that sits on a page.

Crawls and batches both collect many pages, and they suit different starting points. Use a crawl when you have a start URL and a path pattern. Use a batch when you already have the list of URLs, like the `urls` from Step 2.

This step audits your own blog for thin pages.

```
blog_urls = [u for u in urls if BLOG_PATH in u][:100]

batch = client.batches.create(blog_urls)
```

The GEO docs say new accounts are limited to 100 items per batch, which is why the list stops at 100. Higher limits are available on request. To audit a different section, change `BLOG_PATH` in Step 1 to the path your site uses for articles.

```
thin = []
for item in batch.items():  # waits for the batch to finish
    content = item.retrieve(["markdown"])
    words = len((content.markdown_content or "").split())
    if words < 300:
        thin.append((item.url, words))

print(f"{len(thin)} of {len(blog_urls)} posts are under 300 words")
for url, words in sorted(thin, key=lambda r: r[1])[:10]:
    print(f"{words:>6}  {url}")
```

The 300-word cutoff is my choice, so adjust it to your content. The posts at the top of this list are your candidates to expand, merge or redirect.

This is the step that makes the notebook a visibility tool. Olostep's AI search parsers send a prompt to an engine and return structured JSON: the answer as markdown, and the sources it used.

Each batch uses one parser, and you put the prompt in the engine's URL template. Define the engines and your prompts first.

``` python
from urllib.parse import quote_plus

ENGINES = {
    "chatgpt": ("@olostep/chatgpt-results", "https://chatgpt.com/?q={q}"),
    "perplexity": ("@olostep/perplexity-results", "https://www.perplexity.ai/?q={q}"),
    "gemini": ("@olostep/gemini-results", "https://gemini.google.com/?q={q}"),
    "ai_mode": ("@olostep/google-aimode-results", "https://www.google.com/aimode?q={q}"),
    "ai_overview": ("@olostep/google-ai-overview-results", "https://www.google.com/search?q={q}"),
    "copilot": ("@olostep/microsoft-copilot-results", "https://copilot.microsoft.com/chats?q={q}"),
}

PROMPTS = [
    f"best {CATEGORY}",
    f"which {CATEGORY} do developers recommend",
]
```

Replace the two demo prompts with the questions your customers ask, and set `BRAND`, `BRAND_DOMAIN` and `CATEGORY` in Step 1 to your own. Now start one batch per engine. Each item gets a `custom_id`, so you can match results back to prompts.

```
batches = {}
for engine, (parser, template) in ENGINES.items():
    batches[engine] = client.batches.create(
        urls=[
            {"custom_id": str(i), "url": template.format(q=quote_plus(prompt))}
            for i, prompt in enumerate(PROMPTS)
        ],
        parser=parser,
        country="US",
    )
```

Starting every batch before reading any of them lets the engines run side by side. The GEO docs put processing at roughly 20 to 25 minutes, so this is a good moment to make tea. ChatGPT items cost 5 credits each and the other engines cost 3, per the [GEO docs](https://docs.olostep.com/examples/geo). Six engines and two prompts come to 40 credits.

Read each result and score it twice. A **mention** means your brand name appears in the answer text. A **citation** means one of the sources is on your domain.

```
rows = []
cited_domains = Counter()

for engine, batch in batches.items():
    for item in batch.items():  # waits for the batch to finish
        data = item.retrieve(["json"]).json_content or {}
        answer_text = (data.get("answer_markdown") or "").lower()
        sources = [s.get("url", "") for s in data.get("sources") or []]

        cited_domains.update(urlparse(s).netloc for s in sources)
        rows.append({
            "engine": engine,
            "prompt": PROMPTS[int(item.custom_id)],
            "mentioned": BRAND.lower() in answer_text,
            "cited": any(BRAND_DOMAIN in s for s in sources),
            "sources": len(sources),
        })
```

Load the rows into a DataFrame and average the two flags per engine.

``` python
import pandas as pd

df = pd.DataFrame(rows)
print(df.groupby("engine")[["mentioned", "cited"]].mean().round(2))
```

A value of `1.0` means every prompt produced a mention or a citation on that engine, and `0.0` means none did. The two columns tell different stories. A mention without a citation means the engine knows your name and did not use your page. A citation without a mention means it used your page and did not name you.

One last step counts which domains the engines cite for your category.

```
for domain, count in cited_domains.most_common(10):
    print(f"{count:>4}  {domain}")
```

These are the domains AI engines pull from when they answer your category. They can differ from the competitors you found in Step 3, and they are the pages you'd study first.

One run is a snapshot. Save `df` to a CSV with the run date in the filename, rerun the notebook on a schedule you choose, and compare the averages over time. Olostep also has a monitors endpoint that watches pages or queries on a schedule and sends change alerts, if you want to move the tracking out of a notebook.

You now have a notebook that maps your site, finds competitors, audits their content, builds a profile and measures how often six AI engines mention and cite your brand. From here, swap the two demo prompts for your real ones, add competitor names to the mention check, and run the notebook weekly.

To go further, read the [Olostep GEO example](https://docs.olostep.com/examples/geo) for the full output fields per engine, including ads and shopping cards.

**References:**
