抓取页面然后计算某个 class 的 div 数量并回显该数字
Scrape page then count the number of divs of a certain class and echo that number
大家好,我似乎遇到了瓶颈,我正在尝试创建一个简单的脚本来计算当前 运行 此地图的服务器数量,方法是抓取页面,用 class ".row ark_srv1" 然后回显那个数字。
问题:脚本 returns 0
以下是我到目前为止拼凑的内容:
<?php
$html_string = file_get_contents('toparkservers.com/1/search/?term=Umassoura');
function getElementsByClassName($elements, $className) {
$matches = array();
foreach($elements as $element) {
if (!$element->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $element->getAttribute('class'));
if ( ! in_array($className, $classes)) {
continue;
}
$matches[] = $element;
}
return $matches;
}
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = getElementsByClassName($dom->getElementsByTagName('.row ark_srv1'), '.row ark_srv1');
$length = $divs->length;
echo count($divs);
?>
作为替代方案,为什么不使用 xpath
通过 class 名称获取元素:
$html_string = file_get_contents('http://toparkservers.com/1/search/?term=Umassoura');
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html_string);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$class = 'row ark_srv1';
$elements = $xpath->query("//*[contains(@class, '{$class}')]");
echo 'elements found: ', $elements->length;
当我解析 HTML 时,我喜欢使用
XPath.
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$divs= $xpath->query("//div[@class='className']");
echo count($divs);
您可能喜欢使用 QueryPath:
<?php
print html5qp('http://toparkservers.com/1/search/?term=Umassoura', '.row.ark_srv1')->length;
// 9
大家好,我似乎遇到了瓶颈,我正在尝试创建一个简单的脚本来计算当前 运行 此地图的服务器数量,方法是抓取页面,用 class ".row ark_srv1" 然后回显那个数字。
问题:脚本 returns 0
以下是我到目前为止拼凑的内容:
<?php
$html_string = file_get_contents('toparkservers.com/1/search/?term=Umassoura');
function getElementsByClassName($elements, $className) {
$matches = array();
foreach($elements as $element) {
if (!$element->hasAttribute('class')) {
continue;
}
$classes = preg_split('/\s+/', $element->getAttribute('class'));
if ( ! in_array($className, $classes)) {
continue;
}
$matches[] = $element;
}
return $matches;
}
$dom = new DOMDocument;
$dom->loadHTML($html_string);
$divs = getElementsByClassName($dom->getElementsByTagName('.row ark_srv1'), '.row ark_srv1');
$length = $divs->length;
echo count($divs);
?>
作为替代方案,为什么不使用 xpath
通过 class 名称获取元素:
$html_string = file_get_contents('http://toparkservers.com/1/search/?term=Umassoura');
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html_string);
libxml_clear_errors();
$xpath = new DOMXpath($dom);
$class = 'row ark_srv1';
$elements = $xpath->query("//*[contains(@class, '{$class}')]");
echo 'elements found: ', $elements->length;
当我解析 HTML 时,我喜欢使用 XPath.
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$divs= $xpath->query("//div[@class='className']");
echo count($divs);
您可能喜欢使用 QueryPath:
<?php
print html5qp('http://toparkservers.com/1/search/?term=Umassoura', '.row.ark_srv1')->length;
// 9