【发布时间】:2018-05-20 18:55:53
【问题描述】:
PHP 专家,
此脚本有效:
include('simple_html_dom.php');
$html = file_get_html('http://google.com');
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";
//to fetch all images from a webpage
$images = array();
foreach($html->find('img') as $img) {
$images[] = $img->src;
}
print_r($images);
echo "<br />";
//to find h1 headers from a webpage
$headlines = array();
foreach($html->find('h1') as $header) {
$headlines[] = $header->plaintext;
}
print_r($headlines);
echo "<br />";
?>
我没有收到无法识别“查找”的错误。 但是,为什么在我的以下修改中会出现该错误?
<?php
/* FINDING HTML ELEMENTS BASED ON THEIR TAG NAMES
Suppose you wanted to find each and every link on a webpage.
We will be using “find” function to extract this information from the
object. Here’s how to do it using Simple HTML DOM Parser :
*/
include('simple_html_dom.php');
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$html = curl_exec($curl);
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";
?>
我得到错误: 致命错误:未捕获的错误:调用 C:\xampp\htdocs\cURL\crawler.php:24 中字符串上的成员函数 find() 堆栈跟踪:#0 {main} 在 C:\xampp\htdocs\cURL\ 中抛出crawler.php 第 24 行
奇怪!关于第一个有效脚本的“查找”,我为什么没有收到同样的错误?很奇怪! 两个脚本几乎相同。在我的修改版本中,我只是替换了“$html = file_get_html('');”与卷曲。自己看吧。
simple_html_dom.php 文件可以从这里下载: https://sourceforge.net/projects/simplehtmldom/files/ 我把这个dom文件和脚本文件放在同一个目录下。 这意味着,我只是替换了:
//$html = file_get_html('http://nimishprabhu.com');
与:
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$html = curl_exec($curl);
就是这样!
第一次编辑: u_mulder 的代码在一些 url 上工作,但在 yahoo 上没有。这是为什么呢?
$url = 'https://www.yahoo.com';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$response_string = curl_exec($curl);
$html = str_get_html($response_string);
//to fetch all hyperlinks from a webpage
$links = array();
foreach($html->find('a') as $a) {
$links[] = $a->href;
}
print_r($links);
echo "<br />";
【问题讨论】:
标签: php oop dom web-crawler