【发布时间】:2017-06-07 22:01:09
【问题描述】:
我无法让我的抓取工具返回我正在寻找的特定内容。如果我返回 $output,我会看到 digg 好像它托管在我的服务器上,所以我知道我正在正确访问该站点,但我无法访问新 DOM 中的元素。我做错了什么?
<?php
include('simple_html_dom.php');
function curl_download($url) {
$ch = curl_init(); //creates a new cURL resource handle
curl_setopt($ch, CURLOPT_URL, "http://digg.com"); // Set URL to download
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); // Set a referer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true ); // Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_HEADER, 0); // Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Timeout in seconds
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
$html = new simple_html_dom();
$html->load($output, true, false );
foreach($html->find('div.digg-story__kicker') as $article) {
$article_title = $article->find('.digg-story__kicker')->innertext;
return $article_title;
}
echo $article_title;
?>
编辑:好的,愚蠢的错误,我现在正在调用该函数:
$html = curl_download('http://digg.com')
如果我回显 $html,我会看到“镜像站点”,但是当我使用 str_get_html($html) 时,simple_html_dom.php 会说 //get html dom from string我不断收到此错误消息:
致命错误:在第 31 行的 /home/andrew73124/public_html/scraper/scraper.php 中调用成员函数 str_get_html() on null
【问题讨论】:
-
Digg 还在,哇
-
提供的代码 sn-ps 似乎脱节 - 有一个函数
curl_download但它永远不会被调用,它也不返回任何值,因此不清楚$output变量来自哪里 -
哦,我什至没有调用该函数。好的,我需要:'$html = curl_download('digg.com');'调用函数。那返回一个字符串对吗?那么现在我需要将其转换为 DOMDocument 吗?
-
将 $html 作为变量进行双重赋值 - 也许在
$html = new simple_html_dom();$html->load($output, true, false );之前尝试$output=curl_download('http://digg.com') -
这对我有用。
<?php foreach(@DOMDocument::loadHTML(file_get_contents('http://digg.com/'))->getElementsByTagName("div") as $div){ if($div->getAttribute("class")!=='digg-story__kicker'){ continue; } var_dump($div->textContent); }- 就是这样,没有 curl,没有 simple_html_dom.php,没有什么,就是这样。
标签: php curl dom web-scraping