ホームページ  >  記事  >  バックエンド開発  >  スクレイピングリンク用のphpコード

スクレイピングリンク用のphpコード

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-17 06:08:02192ブラウズ

php code for scrape links

PHP を使用して Web ページからリンクを取得するには、file_get_contents 関数を使用して HTML コンテンツを取得し、DOMDocument クラスを使用してそれを解析します。簡単な例を次に示します: サイト : SportsFire

<?php

// Function to scrape links from a given URL
function scrapeLinks($url) {
    // Get the HTML content of the webpage
    $html = file_get_contents($url);

    // Create a new DOMDocument instance
    $dom = new DOMDocument();

    // Suppress errors due to malformed HTML
    libxml_use_internal_errors(true);

    // Load the HTML content
    $dom->loadHTML($html);

    // Clear the errors
    libxml_clear_errors();

    // Create an array to hold the links
    $links = [];

    // Get all <a> elements
    $anchors = $dom->getElementsByTagName('a');

    // Loop through the anchors and collect the href attributes
    foreach ($anchors as $anchor) {
        $href = $anchor->getAttribute('href');
        // Add the link to the array if it's not empty
        if (!empty($href)) {
            $links[] = $href;
        }
    }

    return $links;
}

// Example usage
$url = 'https://www.example.com'; // Change this to the URL you want to scrape
$links = scrapeLinks($url);

// Print the scraped links
foreach ($links as $link) {
    echo $link . PHP_EOL;
}
?>

以上がスクレイピングリンク用のphpコードの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:Vue.js da (ref va reactive) farqi次の記事:なし