首页 > 解决方案 > 使用 simple_html_dom.php 检索气压和其他气候数据

问题描述

我想定期(每天一次左右)收集美国各个气象站的气压读数。使用 simple_html_dom.php,我可以抓取该站点的整个页面,例如 ( https://www.localconditions.com/weather-alliance-nebraska/69301/ )。但是,我不知道如何将其解析为气压读数:在本例中为“30.26”。

这是获取所有 html 的代码。显然 find('Barometer') 元素不起作用。

<?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;
?>

关于如何解析这个的任何建议?

谢谢!

标签: phpparsingweb-scraping

解决方案


正如@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.

推荐阅读