1

尝试从以下位置获取天气数据:http: //metservice.com/maps-radar/local-observations/local-3-hourly-observations

确实在这里找到了有关如何使用 Ghost 抓取动态内容的示例,但我还没有找到如何处理结果。

由于在交互式 shell 中运行时 ghost 似乎有问题,所以我使用

打印(结果)

将输出通过管道传输到文件:

python getMetObservation.py>proper_result

这是我的python代码:

from ghost import Ghost
url = ' http://metservice.com/maps-radar/local-observations/local-3-hourly-observations '
gh = Ghost(wait_timeout=60)
页面,resources = gh.open(url)
结果, 资源 = gh.evaluate("document.getElementsByClassName('obs-content');")
print(result)

在检查文件时,它确实包含我想要的内容,但它也包含大量我不想要的信息。也不清楚如何使用评估返回的变量结果。检查 ghost.py 它似乎是由

self.main_frame.evaluateJavaScript("%s" % script)

在:

def evaluate(self, script):
"""评估页面框架中的脚本。

:param script:要评估的脚本。
"""
返回 (
self.main_frame.evaluateJavaScript("%s" % script),
self._release_last_resources(),
)

当我执行命令时:

document.getElementsByClassName('obs-content');

在 Chromium 控制台中,我得到了正确的响应。

我是python的初学者,但愿意学习。另请注意,如果重要的话,我会在 Ubuntu 下的 python 虚拟环境中运行它。

4

1 回答 1

1

请注意,我将此作为答案发布,因为我当前的解决方案是使用 iMacros 扩展并将网页保存在本地,然后使用 BeautifulSoup 对现在的静态数据执行抓取。

最初的问题是关于如何使用 Ghost 在动态页面上工作,但由于我没有到目前为止,我找到了另一个对其他人有用的解决方案。

iMacro 内容(我将其命名为 GetWeather.iim):

VERSION BUILD=8881205 RECORDER=FX
TAB T=1
URL GOTO=http://www.metservice.com/maps-radar/local-observations/local-3-hourly-observations
WAIT SECONDS=5
SAVEAS TYPE=CPL FOLDER=* FILE=+_{{!NOW:yyyymmdd_hhnnss}}

从 crontab 调用的 shellscript:

#!/bin/bash
export DISPLAY=:0.0
/usr/bin/firefox &
sleep 5 /usr/bin/firefox imacros://run/?m=GetWeather.iim
sleep 10
wmctrl -c "Mozilla Firefox"

连同一个使用 BeautifulSoup 进行实际网络抓取的 python 脚本。

更新了停止Firefox的正确方法,而不按照线程的第一个答案中的说明恢复到安全模式

于 2015-01-04T14:23:49.833 回答