Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用simple_html_dom.php检索气压和其他气候数据_Php_Parsing_Web Scraping - Fatal编程技术网

使用simple_html_dom.php检索气压和其他气候数据

使用simple_html_dom.php检索气压和其他气候数据,php,parsing,web-scraping,Php,Parsing,Web Scraping,我想定期(每天一次左右)收集美国各气象站的气压读数。使用simple_html_dom.php,我可以浏览这个站点的整个页面,例如()。然而,我不知道如何将其解析为气压读数:在本例中为“30.26” 下面是获取所有html的代码。显然,“查找”(“气压计”)元素不起作用 <?php // example of how to use basic selector to retrieve HTML contents include('simple_html_dom.php'); // ge

我想定期(每天一次左右)收集美国各气象站的气压读数。使用simple_html_dom.php,我可以浏览这个站点的整个页面,例如()。然而,我不知道如何将其解析为气压读数:在本例中为“30.26”

下面是获取所有html的代码。显然,“查找”(“气压计”)元素不起作用

<?php
// example of how to use basic selector to retrieve HTML contents
include('simple_html_dom.php');
 
// get DOM from URL or file
$html = file_get_html('https://www.localconditions.com/weather-alliance-nebraska/69301/');

// find all span tags with class=gb1
foreach($html->find('strong') as $e)
 echo $e->outertext . '<HR>';
 
 // get an element representing the second paragraph
$element = $html->find("Barometer");

 echo $e->outertext . '<br>';
        
// extract text from HTML
echo $html->plaintext;
?>

有没有关于如何解析的建议


谢谢

正如@bato3在他的评论中所提到的,使用xpath处理此类查询要好得多。不幸的是,DOMDocument和simplexml(我通常用来解析xml/html)都不能消化这个站点的html(至少在我尝试时不能)。因此,我们必须使用简单的html dom并使用(有些不雅观的)CSS选择器和字符串操作:

$dest = $html->find("//div[class='col-sm-6 col-md-6'] > p:has(> strong)"); 
foreach($dest as $e) {
    $target = $e->innertext;
    if (strpos($target, "Barometer")!== false){
    $pressure = explode("  ", $target);
    echo $pressure[2];
    } 
}
输出:

30.25 inHg.

Barometer
不是有效的HTML元素。如果希望通过文本内容查找,则需要
xpath
功能。顺便说一句:有比
simple\u html\u dom
更好的库来抓取页面。例如
hQuery
允许使用css选择器