php - 使用 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;
?>
关于如何解析这个的任何建议?
谢谢!
解决方案
正如@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.
推荐阅读
- github - 使用 git-lfs 存储的笔记本的 Google Colab 徽章
- reactjs - 在 GraphQL 中,如何创建一个不区分大小写的查询,用于在搜索栏中查找名称?
- android - 我应该在 MainActivity 中创建一个 ViewModel 以便将 MutableLiveData 与 NavigationDrawer 一起使用吗?
- optimization - 将集合和索引定义为别名时出错
- mysql - mysqldump 与选择 *
- html - 你如何让一个 div 有一个活跃的或访问的风格?
- ruby - Chef 库问题从 Chef 12 转换为 Chef 14
- javascript - 从显示名称 Discord JS 中获取 id
- sql - SQL Server:如果记录不存在,则将记录插入表中
- security - 从应用程序模拟用户角色(例如经理、承包商等)向 Amazon Elastic Search 发出 POST 请求