首页 > 解决方案 > 从网页获取源代码时遇到问题

问题描述

我已经编写了一个脚本php来从网页获取 html 内容或源代码,但我无法成功。当我执行我的脚本时,它会打开页面本身。如何获取 html 元素或源代码?

这是脚本:

<?php
include "simple_html_dom.php";
function get_source($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $htmlContent = curl_exec($ch);
    curl_close($ch);
    $dom = new simple_html_dom();
    $dom->load($htmlContent);
    return $dom;
}
$scraped_page = get_source("https://stackoverflow.com/questions/tagged/web-scraping");
echo $scraped_page;
?>

目前我是这样的:

在此处输入图像描述 我的预期输出是这样的:

在此处输入图像描述 顺便说一句,echoing $htmlContent也给了我你在图 1 中看到的内容。

标签: phpcurlweb-scrapingsimple-html-dom

解决方案


推荐阅读