【问题标题】:I'm trying to scrape a specific div with an id on a page我正在尝试在页面上使用 id 抓取特定的 div
【发布时间】:2013-04-02 21:59:22
【问题描述】:

我想抓取页面的内容,实际上只是该页面中的一个 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 试图解决这个问题。

【问题讨论】:

  • 它正在工作。你得到了一个 DOMelement,这是意料之中的。如果你想要那个 div 的内容,那么你需要 $div->innerText 或其他任何东西。

标签: php domdocument web-scraping


【解决方案1】:

你可以用这个:

/**
 * 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');

【讨论】:

  • 谢谢谢谢谢谢!
  • 呵呵 :) 刮得开心! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
  • 2015-05-04
相关资源
最近更新 更多