要使用 php 从网页中抓取链接,您可以使用 file_get_contents 函数来获取 html 内容,然后使用 domdocument 类对其进行解析。这是一个简单的示例:站点:sportsfire
<?php// Function to scrape links from a given URLfunction 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 = ‘www.example.’; // Change this to the URL you want to scrape$links = scrapeLinks($url);// Print the scraped linksforeach ($links as $link) { echo $link . PHP_EOL;}?>
以上就是抓取链接的 php 代码的详细内容,更多请关注范的资源库其它相关文章!
转载请注明:范的资源库 » 抓取链接的php代码