【问题标题】:scraper php returning a blank pagescraper php返回一个空白页
【发布时间】:2025-12-22 14:00:19
【问题描述】:

我是 php 新手,我创建了一个 scraper.php 页面,您可以在其中从“http://www.weather-forecast.com”检索任何给定城市的天气信息。
我跟着教练,我看不出为什么我的代码返回一个空白页,而它应该只返回一个简短的 3 天预测

无论如何...这是我的代码

<?php
$city=$_GET['city'];
$city=str_replace(" ","",$city);
$contents=file_get_contents("http://www.weather-forecast.com/locations/".$city."/forecasts/latest");
preg_match('/3 Day Weather Forest Summary:<\/b>
<span class="phrase">(.*?)</span>',$contents, $matches);
echo $matches[1];
?>

【问题讨论】:

标签: php file-get-contents str-replace


【解决方案1】:

它不是空白,而是脚本中的错误。它可能是空白的,可能是因为您关闭了错误报告。

从这一行开始:

preg_match('/3 Day Weather Forest Summary:<\/b><span class="phrase">(.*?)</span>',$contents, $matches);

您忘记在&lt;/span&gt; 上转义/(应该是&lt;\/span&gt;); preg_match 没有结束分隔符/。 (这里有一个错字,应该是 'Forecast' 而不是 Forest。)

但即使你修复了这些错误,你也不会得到你想要的,因为查看天气预报中的 html 源代码,你会跳过 &lt;\/b&gt; 之后的 &lt;span class="read-more-small"&gt;&lt;span class="read-more-content"&gt;

所以,应该是这样的:

<?php
$city=$_GET['city'];
$city=str_replace(" ","",$city);
$contents=file_get_contents("http://www.weather-forecast.com/locations/".$city."/forecasts/latest");
preg_match('/3 Day Weather Forecast Summary:<\/b><span class="read-more-small"><span class="read-more-content"> <span class="phrase">(.*?)<\/span>/',$contents, $matches);
echo $matches[1];
?>


或者

您可以使用 preg_match_all 获取所有三个天气预报摘要(1 - 3 天、4 - 7 天和 7 - 10 天),方法是将所有 preg_match 行替换为:

preg_match_all('/<span class="phrase">(.*?)<\/span>/',$contents, $matches);

并回显您的数据:

$matches[0][0] 1-3 天,
$matches[0][1] 4-7 天,
$matches[0][2] 7-10 天。

【讨论】:

    【解决方案2】:

    试着回答这个问题:

    how-can-i-emulate-a-get-request-exactly-like-a-web-browser,

    得到你正在寻找的东西。

    说明:

    file_get_contents() 会给你静态页面内容。

    您在浏览器中实际看到的内容是由 HTML/CSS/JS 生成的, 并且不会在 file_get_contents() 函数中看到。

    当我尝试直接从浏览器浏览到该网址时

    (例如:new york

    并作为源打开页面,搜索:“3 Day Weather Forest Summary:”。

    我没有得到任何结果,所以我假设这是你的问题。

    【讨论】: