【问题标题】:Why doesn't this php crawler work?为什么这个 php 爬虫不起作用?
【发布时间】: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


【解决方案1】:

您正在使用某种类型的重音引号字符,例如

这些不是 php 中的有效引号字符。您需要使用常规引号,例如 "'

另外,在考虑编写更多代码之前,您应该配置 php 以显示错误和通知。

【讨论】:

  • 编辑了所有奇怪的引用。我可以听到我的计算机正在获取数据,但我仍然遇到同样的问题,即空 lo​​calhost/welcome?crawlThis=www.google.com
  • 使用var_dump($links);你应该得到一些东西
  • 如果我仍然一无所获,这意味着什么?我的服务器正在工作。 echo "whatever" 打印任何内容。但是我的逻辑中的某些东西似乎正在停止整个页面。了解自己,可能是一个我会忽略 100 次的微小错误。
  • “在考虑编写更多代码之前,您应该配置 php 以显示错误和通知”。想象一下,如果 java 编译器没有给你错误,只是沉默了——这就是你目前的情况。
【解决方案2】:

我完全赞成自己编写它,但是有很多记录在案的示例可以做到这一点。这是一个很好的例子,您可以遵循或使用:

crawler example

【讨论】:

  • 知道为什么当我把你提供的爬虫放在我的本地主机根文件夹中时,它什么也没有显示吗?
  • 没关系,我没有下载他们的库。但问题是,我需要在没有任何外部库的情况下执行此操作。我正在接受测试我在学习新语言的同时编写生产代码的能力 - 和外部库违背了任务的目的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 2012-04-22
  • 1970-01-01
相关资源
最近更新 更多