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 />";
?>
欢迎任何建议和代码示例用于我的学习目的。我是一名自学的学生。
解决方案
原因是您尝试下载的页面 (fiverr.com) 是基于 JavaScript 的,具有动态加载的内容。这在 PHP 中不起作用,因为它只能看到服务器发送的 HTML,它不能解析和运行 JavaScript。因为这是出于学习目的,您可以简单地尝试不同的网站。
但是,如果您想要一个可行的解决方案,您应该查看Selenium。它基本上是一个无头网络浏览器,它可以像其他浏览器一样执行所有操作,包括运行 JavaScript。通过其网络驱动程序,您将能够完全解析诸如 Fiverr.com 之类的网站。
推荐阅读
- python - Python Selenium 无头 Chrome
- excel - 具有多个范围的循环?VBA
- nginx - Gatsbyjs .env.production 变量在浏览器中不可用
- r - 将 R Shiny 书签保存到本地 .url
- vue.js - 如何在 vuejs 中自定义一个 npm 包
- java - Facebook 赞助信息广告创意 | Java SDK
- apache - 在 Ubuntu 上通过 Apache Web 服务器和 DAV 启用 Subversion 访问
- javascript - Django - AJAX Fetch 为每个输入字母发送请求
- python - 二叉树解的最大深度的内存使用
- c++ - 如何在 O(1) 时间内找到堆栈中的最小节点/元素