SEO自动化与Python工具:让重复工作高效运转的技术方案

SEO自动化与Python工具:让重复工作高效运转

为什么SEO需要自动化?

重复性高的SEO任务

自动化的价值

核心SEO自动化工具库

必备Python库

# 基础爬虫和请求
import requests
from bs4 import BeautifulSoup

# 数据分析
import pandas as pd
import numpy as np

# SEO专用
from googlesearch import search  # Google搜索结果
import advertools  # SEO数据分析
import serpapi  # SERP数据API

# 可视化
import matplotlib.pyplot as plt

常用SEO自动化脚本

脚本1:批量页面状态检查

import requests
import pandas as pd
from urllib.parse import urlparse

def check_url_status(urls):
    results = []
    for url in urls:
        try:
            response = requests.get(url, timeout=10, allow_redirects=True)
            final_url = response.url
            status_code = response.status_code
            
            results.append({
                "original_url": url,
                "final_url": final_url,
                "status_code": status_code,
                "redirected": url != final_url
            })
        except Exception as e:
            results.append({
                "original_url": url,
                "final_url": None,
                "status_code": None,
                "error": str(e)
            })
    
    return pd.DataFrame(results)

# 使用
urls_to_check = ["https://example.com/page1", "https://example.com/page2"]
results_df = check_url_status(urls_to_check)
results_df.to_csv("url_status_report.csv", index=False)
print(f"检查完成:{len(results_df)}个URL")

脚本2:批量提取SEO元数据

import requests
from bs4 import BeautifulSoup
import pandas as pd

def extract_seo_metadata(url):
    try:
        response = requests.get(url, timeout=10)
        soup = BeautifulSoup(response.content, "html.parser")
        
        # 提取基础SEO数据
        title = soup.find("title").text.strip() if soup.find("title") else ""
        h1 = soup.find("h1").text.strip() if soup.find("h1") else ""
        
        meta_desc = soup.find("meta", {"name": "description"})
        description = meta_desc["content"] if meta_desc else ""
        
        # 字数统计
        body_text = soup.find("body").get_text() if soup.find("body") else ""
        word_count = len(body_text.split())
        
        # 内链统计
        internal_links = [a["href"] for a in soup.find_all("a", href=True) 
                         if urlparse(a["href"]).netloc == "" or 
                         "yourdomain.com" in urlparse(a["href"]).netloc]
        
        return {
            "url": url,
            "title": title,
            "title_length": len(title),
            "h1": h1,
            "description": description,
            "description_length": len(description),
            "word_count": word_count,
            "internal_link_count": len(internal_links)
        }
    except Exception as e:
        return {"url": url, "error": str(e)}

# 从Sitemap批量提取
sitemap_urls = ["https://example.com/page1", ...]
metadata_df = pd.DataFrame([extract_seo_metadata(url) for url in sitemap_urls])
metadata_df.to_csv("seo_metadata_audit.csv", index=False)

脚本3:竞品内容监控

import feedparser
import hashlib
import json
from datetime import datetime

def monitor_competitor_content(rss_feeds):
    """监控竞品RSS订阅,发现新内容"""
    new_content = []
    
    # 加载已知内容哈希
    try:
        with open("known_content.json", "r") as f:
            known_hashes = json.load(f)
    except FileNotFoundError:
        known_hashes = {}
    
    for feed_url, competitor_name in rss_feeds.items():
        feed = feedparser.parse(feed_url)
        
        for entry in feed.entries:
            content_hash = hashlib.md5(entry.link.encode()).hexdigest()
            
            if content_hash not in known_hashes:
                new_content.append({
                    "competitor": competitor_name,
                    "title": entry.title,
                    "url": entry.link,
                    "published": entry.published if hasattr(entry, "published") else ""
                })
                known_hashes[content_hash] = {
                    "url": entry.link,
                    "discovered_at": datetime.now().isoformat()
                }
    
    # 更新已知内容
    with open("known_content.json", "w") as f:
        json.dump(known_hashes, f, ensure_ascii=False)
    
    return new_content

# 使用示例
rss_feeds = {
    "https://competitor1.com/feed": "竞品A",
    "https://competitor2.com/rss.xml": "竞品B"
}
new_articles = monitor_competitor_content(rss_feeds)
if new_articles:
    print(f"发现{len(new_articles)}篇竞品新内容!")

脚本4:自动Sitemap更新

import xml.etree.ElementTree as ET
from datetime import datetime

def update_sitemap(sitemap_path, new_urls):
    """向Sitemap添加新URL"""
    tree = ET.parse(sitemap_path)
    root = tree.getroot()
    
    namespace = "http://www.sitemaps.org/schemas/sitemap/0.9"
    ET.register_namespace("", namespace)
    
    for url_data in new_urls:
        url_element = ET.SubElement(root, f"{{{namespace}}}url")
        
        loc = ET.SubElement(url_element, f"{{{namespace}}}loc")
        loc.text = url_data["loc"]
        
        lastmod = ET.SubElement(url_element, f"{{{namespace}}}lastmod")
        lastmod.text = url_data.get("lastmod", datetime.now().strftime("%Y-%m-%d"))
        
        priority = ET.SubElement(url_element, f"{{{namespace}}}priority")
        priority.text = str(url_data.get("priority", 0.8))
    
    tree.write(sitemap_path, encoding="UTF-8", xml_declaration=True)
    print(f"Sitemap更新完成,添加了{len(new_urls)}个URL")

Google Search Console API自动化

使用GSC API自动提取数据,避免手动导出:

from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import pandas as pd

def get_gsc_data(site_url, start_date, end_date, dimensions=["query", "page"]):
    """从GSC API提取搜索数据"""
    scopes = ["https://www.googleapis.com/auth/webmasters.readonly"]
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        "service_account.json", scopes
    )
    
    service = build("searchconsole", "v1", credentials=credentials)
    
    request = {
        "startDate": start_date,
        "endDate": end_date,
        "dimensions": dimensions,
        "rowLimit": 25000
    }
    
    response = service.searchanalytics().query(siteUrl=site_url, body=request).execute()
    
    rows = response.get("rows", [])
    data = [{
        **{dim: row["keys"][i] for i, dim in enumerate(dimensions)},
        "clicks": row["clicks"],
        "impressions": row["impressions"],
        "ctr": row["ctr"],
        "position": row["position"]
    } for row in rows]
    
    return pd.DataFrame(data)

# 使用示例
df = get_gsc_data("https://yourdomain.com", "2026-04-27", "2026-05-27")
df.to_csv("gsc_data.csv", index=False)

总结

SEO自动化是提升团队效率的重要手段。以上脚本提供了最常用的SEO自动化起点。建议从批量状态检查和元数据提取开始,逐步建立完整的SEO自动化工作流。随着自动化水平提升,SEO团队可以将更多精力投入到策略思考和内容创作等高价值工作中。