Build an internal link budget allocator: hub scoring, anchor taxonomy, crawl depth…
- User
Build an internal link budget allocator: hub scoring, anchor taxonomy, crawl depth reduction, and simulation toolkit.
Assistant
Build an internal link budget allocator: hub scoring, anchor taxonomy, crawl depth reduction, and simulation toolkit.
The user wants an "internal link budget allocator" toolkit. This is a technical SEO concept. The core components requested are:
I need to structure this as a Python toolkit or a conceptual framework with code snippets, as that's the most useful format for a "build" request. I will assume the user has a dataset of URLs and links (edges).
Component 1: Hub Scoring
networkx is the standard Python library for this.Component 2: Anchor Taxonomy
(source_url, target_url, anchor_text) and returns a classification.Component 3: Crawl Depth Reduction
networkx or scipy.Component 4: Simulation Toolkit (The "Allocator")
Structure of the Response:
pandas, networkx.InternalLinkOptimizer.
__init__: Load graph.calculate_hub_auth: HITs algorithm.analyze_depth: BFS from root.classify_anchors: Regex logic.simulate_flow: PageRank simulation.Refining the Code:
networkx DiGraph (Directed Graph).Self-Correction/Safety Check:
networkx.pagerank for the simulation to keep the code concise.Drafting the Content:
nx.hits.nx.shortest_path_length.AnchorClassifier class or method using Regex.run_scenario(added_links).Let's assemble the Python solution. I will create a single, comprehensive Python class that handles all these requirements.
['source', 'destination', 'anchor_text'].Step-by-step implementation details:
Let's write the code.
This is a comprehensive Python framework for an Internal Link Budget Allocator. It uses networkx for graph theory algorithms to calculate Hub/Authority scores, numpy for matrix simulations (PageRank), and pandas for data wrangling.
This toolkit allows you to:
You will need pandas, networkx, and numpy.
pip install pandas networkx numpy
edge_list_df. It requires a Source URL, Destination URL, and the Anchor Text.calculate_hub_scores): Use this to identify "Power Pages." A page with a high Hub Score links to other important pages. A page with a high Authority Score is linked to by Hubs.
classify_anchor_taxonomy): This checks if you are over-optimizing.
analyze_crawl_depth): Ensure key pages are within 3 clicks of the Home page.
product-d has a depth of 99 (Orphan), it must be linked immediately from the sitemap or main navigation.simulate_link_insertion): Before giving orders to developers, run this. It calculates the theoretical PageRank shift. If delta is negative for your key page, you have a math error (rare in simple addition, but possible if complex loops exist). Usually, you will see a positive delta for the target.import pandas as pd
import networkx as nx
import numpy as np
import re
from collections import Counter
class InternalLinkBudgetAllocator:
def __init__(self, edge_list_df):
"""
Initialize the allocator.
:param edge_list_df: Pandas DataFrame with columns ['source', 'destination', 'anchor_text', 'is_dofollow']
"""
self.raw_df = edge_list_df
self.graph = nx.DiGraph()
# Build Graph
print("Building directed graph...")
for _, row in self.raw_df.iterrows():
self.graph.add_edge(
row['source'],
row['destination'],
anchor=row['anchor_text'],
weight=1 if row.get('is_dofollow', True) else 0
)
# Ensure all nodes exist even if they have no edges (orphan check)
all_nodes = set(self.raw_df['source']).union(set(self.raw_df['destination']))
self.graph.add_nodes_from(all_nodes)
# ---------------------------------------------------------
# 1. HUB & AUTHORITY SCORING (HITS Algorithm)
# ---------------------------------------------------------
def calculate_hub_scores(self):
"""
Calculates HITS scores.
- Hubs: Pages that link to many good Authorities (Good donors).
- Authorities: Pages linked to by many good Hubs.
"""
print("Calculating Hub/Authority scores...")
try:
hubs, authorities = nx.hits(self.graph, max_iter=100, tol=1.0e-6, normalized=True)
hub_df = pd.DataFrame({
"url": list(hubs.keys()),
"hub_score": list(hubs.values()),
"authority_score": [authorities.get(url, 0) for url in hubs.keys()]
}).sort_values(by='hub_score', ascending=False)
return hub_df
except Exception as e:
return pd.DataFrame({"error": [str(e)]})
# ---------------------------------------------------------
# 2. CRAWL DEPTH REDUCTION
# ---------------------------------------------------------
def analyze_crawl_depth(self, root_node):
"""
Calculates shortest path length from the root (Home) to all nodes.
"""
print(f"Calculating crawl depth from root: {root_node}...")
depths = {}
for node in self.graph.nodes():
try:
length = nx.shortest_path_length(self.graph, source=root_node, target=node)
depths[node] = length
except nx.NetworkXNoPath:
depths[node] = 99 # Effectively infinity/orphan
depth_df = pd.DataFrame({
"url": list(depths.keys()),
"crawl_depth": list(depths.values())
}).sort_values(by='crawl_depth', ascending=False)
return depth_df
# ---------------------------------------------------------
# 3. ANCHOR TAXONOMY CLASSIFIER
# ---------------------------------------------------------
def classify_anchor_taxonomy(self, brand_terms=[], money_keywords=[]):
"""
Tags anchors into categories: Exact Match, Partial, Brand, Generic, URL.
"""
print("Classifying anchor taxonomy...")
df = self.raw_df.copy()
def get_type(anchor):
anchor_lower = str(anchor).lower()
# 1. URL Check
if anchor_lower.startswith("http") or anchor_lower.startswith("www."):
return "URL"
# 2. Exact Match (Money Keywords)
for kw in money_keywords:
if kw.lower() == anchor_lower:
return "Exact Match"
# 3. Brand Check
for brand in brand_terms:
if brand.lower() in anchor_lower:
return "Branded"
# 4. Partial Match
for kw in money_keywords:
if kw.lower() in anchor_lower:
return "Partial Match"
# 5. Generic
generics = ['click here', 'read more', 'learn more', 'here']
if anchor_lower in generics:
return "Generic"
return "Misc / Long-tail"
df['anchor_type'] = df['anchor_text'].apply(get_type)
# Aggregate stats
taxonomy = df.groupby('anchor_type').size().reset_index(name='count')
taxonomy['percentage'] = (taxonomy['count'] / taxonomy['count'].sum()) * 100
return taxonomy, df
# ---------------------------------------------------------
# 4. SIMULATION TOOLKIT (PageRank Flow)
# ---------------------------------------------------------
def simulate_link_insertion(self, source_node, target_node, damping=0.85):
"""
Simulates adding a single link and calculates the change in PageRank
for the target node and surrounding nodes.
"""
print(f"Simulating link insertion: {source_node} -> {target_node}")
# 1. Baseline PR
try:
baseline_pr = nx.pagerank(self.graph, alpha=damping)
except:
baseline_pr = {}
# 2. Create Copy and Modify
sim_graph = self.graph.copy()
if not sim_graph.has_edge(source_node, target_node):
sim_graph.add_edge(source, target, weight=1)
# 3. New PR
try:
new_pr = nx.pagerank(sim_graph, alpha=damping)
except:
new_pr = {}
# 4. Compare
results = []
for url in self.graph.nodes():
base = baseline_pr.get(url, 0)
new = new_pr.get(url, 0)
change = new - base
results.append({
"url": url,
"baseline_pr": base,
"new_pr": new,
"delta": change
})
return pd.DataFrame(results).sort_values(by="delta", ascending=False)
# ---------------------------------------------------------
# 5. BUDGET ALLOCATOR (The Strategy)
# ---------------------------------------------------------
def generate_link_plan(self, target_urls, donor_candidates):
"""
Suggests a link plan based on Depth reduction and Hub scores.
"""
print("Generating Link Budget Plan...")
# 1. Get Scores
hub_df = self.calculate_hub_scores()
# 2. Identify high value targets (Low Depth OR High Value but Isolated)
# logic: If a node has high hub score, it passes value.
# We want to link High Hub Pages -> Target Pages.
plan = []
for target in target_urls:
# Find best donor that doesn't currently link to target
potential_donors = hub_df[hub_df['url'].isin(donor_candidates)]
for _, donor in potential_donors.iterrows():
if not self.graph.has_edge(donor['url'], target):
plan.append({
"action": "INSERT_LINK",
"source": donor['url'],
"destination": target,
"rationale": f"Source has Hub Score {donor['hub_score']:.4f} (High Equity)"
})
break # Only take the best donor for this example
return pd.DataFrame(plan)
# =============================================================
# EXAMPLE USAGE
# =============================================================
# 1. Mock Data Creation
data = [
('home', 'products', 'View Products'),
('home', 'blog', 'Read our Blog'),
('home', 'about', 'About Us'),
('products', 'product-a', 'Product A Details'),
('products', 'product-b', 'Product B'),
('blog', 'post-1', 'Read More'), # Generic anchor example
('blog', 'product-a', 'Check out Product A'), # Internal link in blog
('post-1', 'product-b', 'buy cheap widgets'), # Money keyword example
# Orphan page (Deep or disconnected)
('product-c', 'product-d', 'Related Item')
]
df = pd.DataFrame(data, columns=['source', 'destination', 'anchor_text'])
# 2. Initialize Toolkit
toolkit = InternalLinkBudgetAllocator(df)
# 3. Run Hub Scoring
print("\n--- Hub Scores ---")
hubs = toolkit.calculate_hub_scores()
print(hubs.head())
# 4. Run Anchor Taxonomy
print("\n--- Anchor Taxonomy ---")
tax_stats, full_tax_data = toolkit.classify_anchor_taxonomy(
brand_terms=['MyBrand'],
money_keywords=['cheap widgets', 'buy']
)
print(tax_stats)
# 5. Crawl Depth Analysis
print("\n--- Crawl Depth ---")
depths = toolkit.analyze_crawl_depth(root_node='home')
print(depths[depths['crawl_depth'] > 1].head()) # Show deep pages
# 6. Simulate Change
print("\n--- Simulation: Linking Home to Product-D ---")
simulation = toolkit.simulate_link_insertion(source_node='home', target_node='product-d')
print(simulation[simulation['url'] == 'product-d'])
# 7. Generate Plan
print("\n--- Link Budget Plan ---")
# We want to boost 'product-d', using 'home' or 'blog' as donors
plan = toolkit.generate_link_plan(
target_urls=['product-d'],
donor_candidates=['home', 'products']
)
print(plan)