{"slug": "how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep", "title": "How to Build an SEO and AI Search Visibility Workflow in Python with Olostep", "summary": "A developer published a Python workflow using the Olostep web data API to audit search and AI-search visibility, combining site mapping, competitor search, page scraping, crawling, and batch AI-answer tracking in a single Colab notebook. The tutorial demonstrates each Olostep SDK call, including parsers that return structured answers and citations from ChatGPT, Perplexity, Gemini, Google AI Mode, Google AI Overview and Copilot. Sample runs on stripe.com returned 7,437 mapped URLs, with Wise used as the competitor example.", "body_md": "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?\n\nEach 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.\n\nOlostep is a web data API with an endpoint for each of those pulls:\n\nIn addition, its AI search parsers return structured answers and citations from ChatGPT, Perplexity, Gemini, Google AI Mode, Google AI Overview and Copilot.\n\nIn 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.\n\nYou 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)\n\nLet's get started!\n\n`olostep` SDK requires 3.11, docs tested for Python versions 3.11 to 3.13)\nLet's start with an overview of the various Olostep endpoints and their equivalent SDK calls:\n\n| Job | Endpoint | SDK call | \n|---|---|---|\n| Detect site structure | Maps | `client.maps.create()` | \n| Find competitors | Search | `client.searches.create()` | \n| Retrieve one page | Scrapes | `client.scrapes.create()` | \n| Retrieve a section of a site | Crawls | `client.crawls.create()` | \n| Retrieve a researched fact | Answers | `client.answers.create()` | \n| Collect a known URL list at volume | Batches | `client.batches.create()` | \n| Track prompts across AI engines | Batches with AI parsers | `client.batches.create(parser=...)` | \n\nInstall the SDK first.\n\n```\n!pip install -q olostep\n```\n\nNext, 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.\n\n``` python\nimport os\nfrom getpass import getpass\n\nfrom olostep import Olostep  # make sure you've installed the Python SDK\n\n# 1. Retrieve the API key\napi_key = os.getenv(\"OLOSTEP_API_KEY\")\nif not api_key:\n    api_key = getpass(\"Please enter your Olostep API Key: \")\n    os.environ[\"OLOSTEP_API_KEY\"] = api_key\n\n# 2. Initialize the client\nclient = Olostep(api_key=api_key)\n```\n\nThen set the values you'll change for your own project.\n\n```\nSITE = \"https://your-site-here.com\"  # your site\nBRAND = \"Your Brand Here\"  # how people write your brand name\nBRAND_DOMAIN = \"your-site-here.com\"  # your bare domain\nBLOG_PATH = \"/blog/\"  # where your site publishes articles\nCATEGORY = \"your category here\"  # the topic you want to rank and be cited for\n\nCOMPETITOR = \"https://competitor-here.com\"  # one competitor to study\n```\n\n**Note:** Replace each placeholder with your own value before you run anything:\n\n`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.\nThe 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.\n\nStep 5 has two more strings for your competitor's article pages, and it explains how to find them.\n\nA map returns the URLs Olostep finds on a site. For an SEO team, this is the raw material of a content inventory.\n\n```\nsite_map = client.maps.create(url=SITE)\nurls = list(site_map.urls())\nprint(f\"Found {len(urls)} URLs\")\n```\n\nFor the example site, `stripe.com`, this printed:\n\n```\nFound 7437 URLs\n```\n\n`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.\n\n``` python\nfrom collections import Counter\nfrom urllib.parse import urlparse\n\ndef section(url):\n    first = urlparse(url).path.strip(\"/\").split(\"/\")[0]\n    return f\"/{first}\" if first else \"/\"\n\nfor name, count in Counter(section(u) for u in urls).most_common(10):\n    print(f\"{count:>5}  {name}\")\n```\n\nFor `stripe.com`, the ten largest sections looked like this:\n\n```\n3658  /resources\n 1440  /careers\n  590  /customers\n  399  /legal\n  279  /newsroom\n  275  /blog\n  206  /guides\n  170  /sessions\n   57  /payment-method\n   28  /payments\n```\n\nThe 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.\n\nSearch 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.\n\n```\nsearch = client.searches.create(\n    f\"best {CATEGORY}\",\n    limit=10,\n    exclude_domains=[BRAND_DOMAIN],\n)\n\nfor link in search.links:\n    print(urlparse(link[\"url\"]).netloc, \"|\", link[\"title\"])\n```\n\nSample output for the Stripe example:\n\n```\nairwallex.com | 5 best online payment processing services of 2026\nairwallex.com | 5 best payment processors of 2026\nnerdwallet.com | Stripe Review 2026: Features and Pricing - NerdWallet\nwise.com | 7 Cheapest Payment Processing Services for Small Businesses - Wise\nnerdwallet.com | Best Payment Gateways of 2026 - NerdWallet\nwww.forbes.com | 7 Best Payment Gateways – Forbes Advisor\nlearn.g2.com | I Evaluated the 6 Best Payment Processing Software for 2026\ntechrepublic.com | The 6 Best Payment Processing Providers\nnerdwallet.com | 5 Best Payment Processors for Small Business in 2026\nforbes.com | 10 Best Credit Card Processing Companies of 2026 – Forbes Advisor\n```\n\nEach 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`.**\n\nYou 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.\n\n**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.\n\nA scrape converts one URL into clean markdown. Pull the competitor's homepage and look at how it is organized.\n\n```\npage = client.scrapes.create(url_to_scrape=COMPETITOR, formats=[\"markdown\"])\nmarkdown = page.markdown_content\n\nprint(f\"{len(markdown.split())} words\")\nfor line in markdown.splitlines():\n    if line.startswith(\"#\"):\n        print(line)\n```\n\nThis 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.\n\nA 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.\n\nTwo strings in the code below are yours to replace:\n\n`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/**`.\n\n```\nCOMPETITOR_START = \"https://competitor-here.com/blog/\"  # replace with your competitor's article listing page\nCOMPETITOR_PATTERN = \"/blog/**\"  # replace with the path their articles share\n\ncrawl = client.crawls.create(\n    start_url=COMPETITOR_START,\n    include_urls=[COMPETITOR_PATTERN],\n    max_pages=25,\n)\n```\n\n`crawl.pages()` waits for the crawl to finish, then yields each page. Retrieve the markdown for each one and count the words.\n\n```\nrows = []\nfor post in crawl.pages():\n    content = post.retrieve([\"markdown\"])\n    words = len((content.markdown_content or \"\").split())\n    rows.append((post.url, words))\n\nfor url, words in sorted(rows, key=lambda r: r[1], reverse=True)[:10]:\n    print(f\"{words:>6}  {url}\")\n```\n\nYou 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.\n\nSome 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.\n\n```\nanswer = client.answers.create(\n    task=f\"What does {COMPETITOR} sell, who is it for, and how is it priced?\",\n    json_format={\"product\": \"\", \"audience\": \"\", \"pricing\": \"\"},\n)\nprint(answer.json_content[\"product\"])\n```\n\n**But what happens when you index into the result?**\n\n**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.\n\n**The solution:** parse it with `json.loads`.\n\n``` python\nimport json\n\nprofile = json.loads(answer.json_content)\nprint(profile)\nprint(answer.sources)\n```\n\n`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.\n\nAn 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.\n\nCrawls 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.\n\nThis step audits your own blog for thin pages.\n\n```\nblog_urls = [u for u in urls if BLOG_PATH in u][:100]\n\nbatch = client.batches.create(blog_urls)\n```\n\nThe 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.\n\n```\nthin = []\nfor item in batch.items():  # waits for the batch to finish\n    content = item.retrieve([\"markdown\"])\n    words = len((content.markdown_content or \"\").split())\n    if words < 300:\n        thin.append((item.url, words))\n\nprint(f\"{len(thin)} of {len(blog_urls)} posts are under 300 words\")\nfor url, words in sorted(thin, key=lambda r: r[1])[:10]:\n    print(f\"{words:>6}  {url}\")\n```\n\nThe 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.\n\nThis 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.\n\nEach batch uses one parser, and you put the prompt in the engine's URL template. Define the engines and your prompts first.\n\n``` python\nfrom urllib.parse import quote_plus\n\nENGINES = {\n    \"chatgpt\": (\"@olostep/chatgpt-results\", \"https://chatgpt.com/?q={q}\"),\n    \"perplexity\": (\"@olostep/perplexity-results\", \"https://www.perplexity.ai/?q={q}\"),\n    \"gemini\": (\"@olostep/gemini-results\", \"https://gemini.google.com/?q={q}\"),\n    \"ai_mode\": (\"@olostep/google-aimode-results\", \"https://www.google.com/aimode?q={q}\"),\n    \"ai_overview\": (\"@olostep/google-ai-overview-results\", \"https://www.google.com/search?q={q}\"),\n    \"copilot\": (\"@olostep/microsoft-copilot-results\", \"https://copilot.microsoft.com/chats?q={q}\"),\n}\n\nPROMPTS = [\n    f\"best {CATEGORY}\",\n    f\"which {CATEGORY} do developers recommend\",\n]\n```\n\nReplace 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.\n\n```\nbatches = {}\nfor engine, (parser, template) in ENGINES.items():\n    batches[engine] = client.batches.create(\n        urls=[\n            {\"custom_id\": str(i), \"url\": template.format(q=quote_plus(prompt))}\n            for i, prompt in enumerate(PROMPTS)\n        ],\n        parser=parser,\n        country=\"US\",\n    )\n```\n\nStarting 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.\n\nRead 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.\n\n```\nrows = []\ncited_domains = Counter()\n\nfor engine, batch in batches.items():\n    for item in batch.items():  # waits for the batch to finish\n        data = item.retrieve([\"json\"]).json_content or {}\n        answer_text = (data.get(\"answer_markdown\") or \"\").lower()\n        sources = [s.get(\"url\", \"\") for s in data.get(\"sources\") or []]\n\n        cited_domains.update(urlparse(s).netloc for s in sources)\n        rows.append({\n            \"engine\": engine,\n            \"prompt\": PROMPTS[int(item.custom_id)],\n            \"mentioned\": BRAND.lower() in answer_text,\n            \"cited\": any(BRAND_DOMAIN in s for s in sources),\n            \"sources\": len(sources),\n        })\n```\n\nLoad the rows into a DataFrame and average the two flags per engine.\n\n``` python\nimport pandas as pd\n\ndf = pd.DataFrame(rows)\nprint(df.groupby(\"engine\")[[\"mentioned\", \"cited\"]].mean().round(2))\n```\n\nA 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.\n\nOne last step counts which domains the engines cite for your category.\n\n```\nfor domain, count in cited_domains.most_common(10):\n    print(f\"{count:>4}  {domain}\")\n```\n\nThese 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.\n\nOne 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.\n\nYou 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.\n\nTo 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.\n\n**References:**", "url": "https://wpnews.pro/news/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep", "canonical_source": "https://dev.to/balapriya/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep-2hgp", "published_at": "2026-11-25 03:30:05+00:00", "updated_at": "2026-11-25 03:42:19.356371+00:00", "lang": "en", "topics": ["generative-engine-optimization", "ai-search", "ai-crawlers", "developer-tools"], "entities": ["Olostep", "ChatGPT", "Perplexity", "Gemini", "Google AI Mode", "Google AI Overview", "Copilot", "Stripe"], "also_reported_by": [], "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.", "recommendation": null, "alternates": {"html": "https://wpnews.pro/news/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep", "markdown": "https://wpnews.pro/news/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep.md", "text": "https://wpnews.pro/news/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep.txt", "jsonld": "https://wpnews.pro/news/how-to-build-an-seo-and-ai-search-visibility-workflow-in-python-with-olostep.jsonld"}}