【发布时间】:2012-12-24 19:47:20
【问题描述】:
在我的 localhost 文档根目录中:
抓取.html
<html>
<body>
<p>
<form action="welcome.php" method="get">
Site to crawl: <input type="text" name="crawlThis">
<input type="submit">
</form>
</p>
</body>
</html>
欢迎.php
<html>
<body>
<?php
include ("crawler.php");
echo $crawl = new Crawler($_GET["crawlThis"]);
$images = $crawl->get("images");
$links = $crawl->get("links");
echo $links;
echo $images;
?>
<br>
</body>
</html>
和 crawler.php
<?php
class Crawler {
protected $markup = '';
public function __construct($uri) {
$this->markup = $this->getMarkup($uri);
}
public function getMarkup($uri) {
return file_get_contents($uri);
}
public function get($type) {
$method = "_get_{$type}";
if (method_exists($this, $method)){
return call_user_method($method, $this);
}
}
protected function _get_images() {
if (!empty($this->markup)){
preg_match_all('/<img([^>]+)\/>/i', $this->markup, $images);
return !empty($images[1]) ? $images[1] : FALSE;
}
}
protected function _get_links() {
if (!empty($this->markup)){
preg_match_all('/<a([^>]+)\>(.*?)\<\/a\>/i', $this->markup, $links);
return !empty($links[1]) ? $links[1] : FALSE;
}
}
}
/*$crawl = new Crawler($);
$images = $crawl->get('images');
$links = $crawl->get('links');*/
?>
结果页面只是空的。 无法弄清楚我是否无法回显 $images,或者我的逻辑是否错误。 我期待一个图像列表,然后是一个链接列表。
另外,我必须包含 crawler.php 还是 php 会在其容器目录中搜索同名的类?
抱歉,从 Java 转到 PHP 有点麻烦。
【问题讨论】:
-
当心,用正则表达式解析 HTML leads to invasions by the elder gods。请看htmlparsing.com/php.html
-
这是一个错误,或者只是 Stack Overflow 做事的方式或只是我,但为什么脚本中的撇号“而不是”?这可能与为什么脚本不起作用有关吗?为什么不是'?尝试纠正它,看看它会做什么......
-
除非有任何 === 类型/值比较,否则我认为即使交换 ' 和 " 也可以。但我什至还没有 PHP 调试器,所以我没有一个人说话。
-
用标准化的'和"重写并重新测试了程序。结果没有区别,根本没有。
标签: php web-crawler