🔍 搜索引擎优化

📋 功能说明
  • 批量查询关键词排名
  • 分析网站SEO状态
  • 检测死链和错误页面
💻 源代码
import requests
from bs4 import BeautifulSoup
import re

def check_google_rank(keyword, domain):
    """检查Google关键词排名"""
    url = f'https://www.google.com/search?q={keyword}'
    headers = {'User-Agent': 'Mozilla/5.0'}
    
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser')
    
    results = soup.select('.g')
    for i, result in enumerate(results, 1):
        link = result.select_one('.yuRUbf a')
        if link and domain in link['href']:
            return i
    return None

def check_broken_links(url):
    """检测死链"""
    headers = {'User-Agent': 'Mozilla/5.0'}
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser')
    
    broken = []
    for link in soup.find_all('a', href=True):
        href = link['href']
        if href.startswith('http'):
            try:
                r = requests.head(href, headers=headers, timeout=5)
                if r.status_code >= 400:
                    broken.append(href)
            except:
                broken.append(href)
    return broken

def analyze_seo(url):
    """SEO分析"""
    headers = {'User-Agent': 'Mozilla/5.0'}
    res = requests.get(url, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser')
    
    analysis = {
        'title': soup.title.string if soup.title else None,
        'meta_desc': soup.find('meta', attrs={'name': 'description'})['content'] if soup.find('meta', attrs={'name': 'description'}) else None,
        'h1_count': len(soup.find_all('h1')),
        'img_without_alt': len([img for img in soup.find_all('img') if not img.get('alt')])
    }
    return analysis

# 示例
rank = check_google_rank('Python教程', 'example.com')
print(f"排名: {rank}")
📦 运行环境
pip install requests beautifulsoup4
功能特点
  • ✅ 关键词排名查询
  • ✅ 死链检测
  • ✅ SEO分析