我用 Python + AI 做了一套 SEO 优化工具:从关键词挖掘到排名监控,流量翻倍的秘密

我用 Python + AI 做了一套 SEO 优化工具:从关键词挖掘到排名监控,流量翻倍的秘密

适合做网站、博客、内容平台,想通过 SEO 获取免费流量的开发者和运营。

本文用 Python + AI 搭了一套完整的 SEO 工具链,从关键词挖掘到内容优化到排名监控。

背景:SEO 是最持久的流量来源

付费广告一停,流量就没了。SEO 不一样------好的内容可以在搜索引擎上持续获得免费流量,几个月甚至几年。

但 SEO 有很多重复性工作:挖掘关键词、分析竞品、优化内容、监控排名。用 Python 自动化这些工作,效率提升 10 倍。

工具链架构

复制代码
关键词挖掘 → 竞品分析 → 内容优化 → 排名监控 → 报告生成

模块 1:关键词挖掘

python 复制代码
import requests
from bs4 import BeautifulSoup
from collections import Counter
import re

class KeywordMiner:
    """关键词挖掘器"""

    def mine_from_search(self, seed_keyword, num_results=10):
        """从搜索引擎结果挖掘关键词"""
        # 搜索结果页的"相关搜索"
        related = self._get_related_searches(seed_keyword)

        # 搜索建议
        suggestions = self._get_search_suggestions(seed_keyword)

        # 合并去重
        all_keywords = list(set(related + suggestions))
        return all_keywords

    def _get_related_searches(self, keyword):
        """获取相关搜索"""
        # 简化实现:实际可以用搜索 API
        url = f"https://www.baidu.com/s?wd={keyword}"
        try:
            resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
            soup = BeautifulSoup(resp.text, "html.parser")
            # 提取相关搜索词
            related = [a.get_text() for a in soup.select(".rs-link")]
            return related[:20]
        except:
            return []

    def _get_search_suggestions(self, keyword):
        """获取搜索建议(自动补全)"""
        url = f"https://suggestion.baidu.com/su?wd={keyword}&action=opensearch"
        try:
            resp = requests.get(url, timeout=5)
            data = resp.json()
            return data[1] if len(data) > 1 else []
        except:
            return []

    def analyze_keywords(self, keywords):
        """分析关键词价值"""
        results = []
        for kw in keywords:
            results.append({
                "keyword": kw,
                "length": len(kw),
                "words": len(kw.split()),
                "has_number": bool(re.search(r'\d', kw)),
                "is_question": any(q in kw for q in ["怎么", "如何", "什么是", "为什么"])
            })
        return sorted(results, key=lambda x: x["length"])

模块 2:竞品分析

python 复制代码
class CompetitorAnalyzer:
    """竞品内容分析器"""

    def analyze_url(self, url):
        """分析竞品页面"""
        try:
            resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
            soup = BeautifulSoup(resp.text, "html.parser")

            # 提取标题
            title = soup.find("title")
            title = title.get_text() if title else ""

            # 提取描述
            meta_desc = soup.find("meta", attrs={"name": "description"})
            description = meta_desc["content"] if meta_desc else ""

            # 提取正文
            body = soup.find("body")
            text = body.get_text() if body else ""

            # 提取关键词密度
            words = re.findall(r'[\u4e00-\u9fff]+', text)
            word_freq = Counter(words)

            # 提取 H 标签
            h_tags = {}
            for i in range(1, 4):
                tags = soup.find_all(f"h{i}")
                h_tags[f"h{i}"] = [t.get_text() for t in tags]

            return {
                "url": url,
                "title": title,
                "description": description,
                "word_count": len(text),
                "top_keywords": word_freq.most_common(20),
                "h_tags": h_tags,
                "has_images": len(soup.find_all("img")) > 0,
                "has_code": len(soup.find_all("code")) > 0 or len(soup.find_all("pre")) > 0
            }
        except Exception as e:
            return {"url": url, "error": str(e)}

    def compare_urls(self, urls):
        """对比多个竞品页面"""
        results = []
        for url in urls:
            analysis = self.analyze_url(url)
            results.append(analysis)

        # 对比表格
        comparison = {
            "titles": [r.get("title", "") for r in results],
            "word_counts": [r.get("word_count", 0) for r in results],
            "has_code": [r.get("has_code", False) for r in results],
        }
        return results, comparison

模块 3:内容优化建议

python 复制代码
def generate_seo_suggestions(article, target_keyword):
    """用 AI 生成 SEO 优化建议"""
    prompt = f"""你是一个 SEO 专家。分析以下文章,给出针对关键词 "{target_keyword}" 的优化建议。

文章标题:{article.get('title', '')}
文章内容(前 1000 字):{article.get('content', '')[:1000]}

请从以下维度分析:
1. 标题是否包含关键词?建议如何优化?
2. 开头 100 字是否包含关键词?
3. 关键词密度是否合理(2-5%)?
4. 是否有 H2/H3 结构化标题?
5. 是否有内部/外部链接建议?
6. Meta Description 建议(150 字以内)

输出格式:
- 每个维度给出当前状态 + 优化建议
- 总体 SEO 得分(1-100)"""

    from openai import OpenAI
    client = OpenAI()
    response = client.chat.completions.create(
        model="gpt-4",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.3
    )
    return response.choices[0].message.content

模块 4:排名监控

python 复制代码
class RankMonitor:
    """排名监控器"""

    def __init__(self, db_path="seo_monitor.db"):
        import sqlite3
        self.db = sqlite3.connect(db_path)
        self.db.execute("""
            CREATE TABLE IF NOT EXISTS rankings (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                keyword TEXT,
                url TEXT,
                position INTEGER,
                checked_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
        """)
        self.db.commit()

    def check_rank(self, keyword, target_url, search_engine="baidu"):
        """检查关键词排名"""
        if search_engine == "baidu":
            return self._check_baidu(keyword, target_url)
        return None

    def _check_baidu(self, keyword, target_url):
        """百度排名检查"""
        url = f"https://www.baidu.com/s?wd={keyword}&rn=50"
        try:
            resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
            soup = BeautifulSoup(resp.text, "html.parser")

            # 提取搜索结果
            results = soup.select(".result h3 a")
            for i, result in enumerate(results):
                href = result.get("href", "")
                text = result.get_text()
                if target_url in href or target_url in text:
                    position = i + 1
                    self.db.execute(
                        "INSERT INTO rankings (keyword, url, position) VALUES (?, ?, ?)",
                        (keyword, target_url, position)
                    )
                    self.db.commit()
                    return position

            return None  # 未找到
        except Exception as e:
            print(f"检查失败: {e}")
            return None

    def get_history(self, keyword, url, days=30):
        """获取排名历史"""
        cursor = self.db.execute(
            """SELECT position, checked_at FROM rankings
               WHERE keyword = ? AND url = ?
               AND checked_at > datetime('now', ?)
               ORDER BY checked_at""",
            (keyword, url, f"-{days} days")
        )
        return cursor.fetchall()

    def generate_report(self, keywords, target_url):
        """生成排名报告"""
        report = []
        for kw in keywords:
            rank = self.check_rank(kw, target_url)
            history = self.get_history(kw, target_url, days=7)

            report.append({
                "keyword": kw,
                "current_rank": rank,
                "trend": self._calculate_trend(history),
                "history": history
            })

        return report

    def _calculate_trend(self, history):
        if len(history) < 2:
            return "→"
        recent = history[0][0]
        older = history[-1][0]
        if recent < older:
            return "↑"  # 排名上升
        elif recent > older:
            return "↓"  # 排名下降
        return "→"

模块 5:完整 SEO 工具

python 复制代码
def run_seo_workflow(target_url, target_keyword):
    """完整 SEO 工作流"""
    print("🔍 SEO 优化工作流启动\n")

    # 1. 关键词挖掘
    print("Step 1: 关键词挖掘...")
    miner = KeywordMiner()
    keywords = miner.mine_from_search(target_keyword)
    print(f"  发现 {len(keywords)} 个相关关键词")

    # 2. 竞品分析
    print("\nStep 2: 竞品分析...")
    # 实际使用时替换为真实竞品 URL
    competitor_urls = [
        "https://competitor1.com/article",
        "https://competitor2.com/article",
    ]
    analyzer = CompetitorAnalyzer()
    results, comparison = analyzer.compare_urls(competitor_urls)
    print(f"  分析了 {len(results)} 个竞品页面")

    # 3. 内容优化建议
    print("\nStep 3: 内容优化建议...")
    article = {"title": "示例文章标题", "content": "文章内容..."}
    suggestions = generate_seo_suggestions(article, target_keyword)
    print(f"  生成了优化建议")

    # 4. 排名监控
    print("\nStep 4: 排名监控...")
    monitor = RankMonitor()
    report = monitor.generate_report(keywords[:5], target_url)
    for item in report:
        rank = item["current_rank"] or "未上榜"
        print(f"  {item['keyword']}: 排名 {rank} {item['trend']}")

    print("\n✅ SEO 工作流完成!")
    return report

踩坑记录

坑 1:搜索引擎反爬

症状:批量查询排名时被封 IP。

解决:控制请求频率(每次间隔 5-10 秒),使用代理 IP 轮换。

坑 2:排名数据不准

症状:同一个关键词,不同时间查结果不同。

原因:搜索引擎有个性化推荐、地域差异。

解决:用无痕模式、固定地域、多次查询取平均值。

坑 3:关键词密度计算不准

症状:中文分词不准确,关键词密度计算有偏差。

解决:用 jieba 分词库替代简单正则匹配。

坑 4:AI 优化建议太泛

症状:AI 说"建议优化标题",但没给具体方案。

解决:在 prompt 里要求 AI 给出具体的修改后标题示例。

坑 5:排名监控不及时

症状:排名变化了但一周后才发现。

解决:设置定时任务,每天自动检查排名变化并发送通知。

总结

3 条核心经验:

  1. 长尾关键词更容易排名。"Python 自动化脚本"比"Python"更容易排到首页。优先优化长尾词。

  2. 内容质量 > 关键词堆砌。搜索引擎越来越智能,堆砌关键词反而会被惩罚。写对用户有价值的内容才是王道。

  3. 排名监控要持续做。SEO 是长期工程,不是一次性优化。持续监控排名变化,发现问题及时调整。


你有做 SEO 优化吗?有什么经验?评论区交流。