【问题标题】:Python: Using Ghost for dynamic webscrapingPython:使用 Ghost 进行动态网页抓取
【发布时间】:2015-02-27 13:33:17
【问题描述】:

试图从http://metservice.com/maps-radar/local-observations/local-3-hourly-observations获取天气数据

确实找到了示例 here 关于如何使用 Ghost 抓取网页动态内容,但我还没有找到如何处理结果。

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

打印(结果)

通过管道输出到文件:

python getMetObservation.py >proper_result

这是我的python代码:

从幽灵导入幽灵
网址 = 'http://metservice.com/maps-radar/local-observations/local-3-hourly-observations'
gh = Ghost(wait_timeout=60)
页面,资源 = gh.open(url)
结果,资源 = gh.evaluate("document.getElementsByClassName('obs-content');")
打印(结果)

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

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

在:

def 评估(自我,脚本):
"""评估页面框架中的脚本。

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

当我执行命令时:

document.getElementsByClassName('obs-content');

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

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

【问题讨论】:

    标签: python dynamic web-scraping ghost.py


    【解决方案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"

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

    按照thread的第一个回答中的说明,更新了停止firefox的正确方法,没有它恢复到安全模式

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-29
      • 2021-11-15
      • 2021-11-29
      • 2021-03-09
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多