Python:使用 Ghost 进行动态网页抓取

标签 python dynamic web-scraping ghost.py

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

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

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

print(result)

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

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)
page, resources = gh.open(url)
result, resources = gh.evaluate("document.getElementsByClassName('obs-content');")
print(result)

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

处理的

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

在:

def evaluate(self, script):
"""Evaluates script in page frame.

:param script: The script to evaluate.
"""
return (
self.main_frame.evaluateJavaScript("%s" % script),
self._release_last_resources(),
)

当我执行命令时:

document.getElementsByClassName('obs-content');

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

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

最佳答案

请注意,我将此作为答案发布,因为我当前的解决方案是使用 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 的正确方法,而不将其恢复到安全模式。

关于Python:使用 Ghost 进行动态网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27721488/

相关文章:

python - 我如何将数据保存在文本文件python中

Javascript:在为动态创建的对象设置 onClick 处理程序时避免 eval()

java - 如何正确处理404页面未找到错误?

html - 如何使用 BeautifulSoup 在 Python 中隔离只有一到两位数的解析结果

python - 将嵌套字典中的 numpy 数组转换为列表,同时保留字典结构

Python - 循环仍在继续

python - Python的数学错误?

c++ - C++ 中的 new 与 *new

php - 下拉菜单和 where 语句

javascript - 使用 JavaScript 进行网页抓取?