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

Patricia Arquette
リリース: 2024-10-17 06:08:02
オリジナル
192 人が閲覧しました

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 サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!