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



我想定期(大约每天一次(收集美国各个气象站的气压读数。例如,使用simple_html_dom.php,我可以抓取这个网站的整个页面(https://www.localconditions.com/weather-alliance-nebraska/69301/)。然而,我不知道如何将其解析为气压读数:在这种情况下;30.26";。

这是获取所有html的代码。显然find("气压计"(元素不起作用。

<?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(至少在我尝试时没有(。因此,我们必须使用simple_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.

相关内容

最新更新