You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP抓取网站全部页面并获取meta description?

抓取全站页面的Meta Description解决方案

一、核心思路

要实现抓取网站所有页面的Meta Description,需要分两步完成:

  • 解析单个页面的Meta Description内容
  • 获取全站所有页面的URL并遍历处理

二、单个页面Meta Description提取函数

使用DOMDocument解析HTML(比正则表达式更稳定,兼容不规范页面代码),结合WordPress官方HTTP请求函数wp_remote_get(避免file_get_contents的兼容性问题):

function get_meta_description_from_url($url) {
    // 发起HTTP请求获取页面内容
    $response = wp_remote_get($url);
    
    // 处理请求错误
    if (is_wp_error($response)) {
        return false;
    }
    
    $html = wp_remote_retrieve_body($response);
    $dom = new DOMDocument();
    
    // 抑制HTML解析时的警告(兼容不规范的页面代码)
    @$dom->loadHTML($html);
    $meta_tags = $dom->getElementsByTagName('meta');
    
    // 遍历meta标签查找description
    foreach ($meta_tags as $tag) {
        if ($tag->getAttribute('name') === 'description') {
            return $tag->getAttribute('content');
        }
    }
    
    // 未找到时返回null
    return null;
}

三、全站页面遍历与批量抓取

通过WordPress的get_posts函数获取所有已发布的页面/文章URL,逐个调用提取函数:

add_action('woocommerce_before_single_product', 'fetch_all_page_meta_descriptions');

function fetch_all_page_meta_descriptions() {
    // 配置要抓取的内容类型和状态
    $args = array(
        'post_type' => array('page', 'post'), // 可添加自定义文章类型(如产品'product')
        'post_status' => 'publish',
        'posts_per_page' => -1, // 获取全部内容
    );
    
    $posts = get_posts($args);
    $meta_descriptions = array();
    
    // 遍历所有页面
    foreach ($posts as $post) {
        $page_url = get_permalink($post->ID);
        $page_desc = get_meta_description_from_url($page_url);
        
        $meta_descriptions[$page_url] = $page_desc;
    }
    
    // 输出结果(可改为写入文件或数据库)
    echo '<pre>';
    print_r($meta_descriptions);
    echo '</pre>';
}

四、关键注意事项

  • 兼容性:用wp_remote_get替代file_get_contents,避免服务器禁用allow_url_fopen导致的请求失败
  • 性能优化:如果网站页面数量大,建议添加分批处理逻辑,或者将结果缓存到数据库,避免重复请求消耗资源
  • 内容范围:调整post_type参数可扩展到自定义文章类型,适配不同业务需求
  • 错误处理:函数中添加了请求错误判断,避免单个页面失败导致整个流程中断

内容的提问来源于stack exchange,提问作者Fazal Mehmood

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:35:28