首页 > 解决方案 > 数组编号问题

问题描述

为什么此代码能够从以下第一页获取数据并通过对数组进行编号将它们插入到数组中,而对于以下第二页却无法执行相同操作:

http://nimishprabhu.com

https://www.fiverr.com/search/gigs?utf8=%E2%9C%93&source=guest-homepage&locale=en&search_in=everywhere&query=php

该页面显示的数组编号如下,这是不正确的:

Array ( [0] => mailto:support@fiverr.com ) 
Array ( [0] => https://collector.fiverr.com/api/v1/collector/noScript.gif?appId=PXK3bezZfO
        [1] => https://collector.fiverr.com/api/v1/collector/pxPixel.gif?appId=PXK3bezZfO ) 
Array ( [0] => One Small Step )

代码:

<?php

/*
2.
FINDING HTML ELEMENTS BASED ON THEIR TAG NAMES

Suppose you wanted to find each and every image on a webpage or say, each 
and every hyperlink. 
We will be using “find” function to extract this information from the 
object. Doing it using Simple HTML DOM Parser :
*/

include('simple_html_dom.php');

$html = file_get_html('https://www.fiverr.com/search/gigs?utf8=%E2%9C%93&source=guest-homepage&locale=en&search_in=everywhere&query=php');

//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 />";

?>

欢迎任何建议和代码示例用于我的学习目的。我是一名自学的学生。

标签: phparrays

解决方案


原因是您尝试下载的页面 (fiverr.com) 是基于 JavaScript 的,具有动态加载的内容。这在 PHP 中不起作用,因为它只能看到服务器发送的 HTML,它不能解析和运行 JavaScript。因为这是出于学习目的,您可以简单地尝试不同的网站。

但是,如果您想要一个可行的解决方案,您应该查看Selenium。它基本上是一个无头网络浏览器,它可以像其他浏览器一样执行所有操作,包括运行 JavaScript。通过其网络驱动程序,您将能够完全解析诸如 Fiverr.com 之类的网站。


推荐阅读