php - 我正在尝试在页面上抓取带有 id 的特定 div

标签 php domdocument web-scraping

我想抓取页面的内容,实际上只是该页面的一个 div,然后在网页上的一个小 div 中将其显示给用户。我只需要来自需要用户凭据的 carfax 页面的一条信息,因此我无法发布确切的代码,但我尝试使用 google.com 并遇到了同样的问题,因此解决方案应该交叉。

现在我试过这个:

$webPage = file_get_contents('http://www.google.com');
$doc = new DOMDocument();
$doc->loadHTML($webPage);
$div = $doc->getElementById('lga');//this is the id to the div holding the image above the textbox
//echo $webPage;//this displays www.google.com minus the image. I imagine because of the file path
//var_dump($div);//this display "object(DOMElement)#2 (0) { }" and I'm not sure what that means
//echo $div;//this has a server error

我也在查看 simple_html_dom.php 试图解决这个问题。

最佳答案

你可以使用这个:

/**
 * Downloads a web page from $url, selects the the element by $id
 * and returns it's xml string representation.
 */
function getElementByIdAsString($url, $id, $pretty = true) {
    $doc = new DOMDocument();
    @$doc->loadHTMLFile($url);

    if(!$doc) {
        throw new Exception("Failed to load $url");
    }

    // Obtain the element
    $element = $doc->getElementById($id);

    if(!$element) {
        throw new Exception("An element with id $id was not found");
    }

    if($pretty) {
        $doc->formatOutput = true;
    }

    // Return the string representation of the element
    return $doc->saveXML($element);
}

// call it:
echo getElementByIdAsString('http://www.google.com', 'lga');

关于php - 我正在尝试在页面上抓取带有 id 的特定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15775192/

相关文章:

python - TELNETCONSOLE_ENABLED 设置为 True 但所需的扭曲模块无法导入

excel - 最小化窗口驱动程序 selenium excel vba

php - 如何在ie7中设置兼容性 View ?

php - 如何在 Laravel 模型关系中传递参数

PHP 命名空间未在同一目录中的同一命名空间中找到类 - 在开发中工作,而不是在生产中

php - php中DOMDocument的编码问题

php - 如何获取 DOMElement 节点的 html 代码?

php - SQL Comment表插入语句

javascript - foreach 中的 DomDocument removeChild 重新索引 dom

r - 用 r 抓取 ajax 站点