gpt4 book ai didi

python - 如何通过 GhostDriver (selenium) 使用 PhantomJS 运行网页代码

转载 作者:太空狗 更新时间:2023-10-29 20:56:15 29 4
gpt4 key购买 nike

我正在寻找通过 GhostDriver 使用 PhantomJS 渲染 pdf 的能力,而不仅仅是渲染 pdf。当我使用下一个代码时,页面正常加载:

from selenium import webdriver

driver = webdriver.PhantomJS('./node_modules/phantomjs/bin/phantomjs')
driver.set_window_size(1024, 768)
driver.get('http://stackoverflow.com')

当我通过命令行使用下一个脚本时 https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js然后完美生成pdf。

现在我想通过 webdriver 执行类似 rasterize.js (page.render('file.pdf')) 的脚本。 webdriverexecute_script 方法,但它看起来像 PhantomJS 代码评估,无法访问 webpage 实例上下文。 webdriver 也有 get_screenshot_as_base64 方法,但它只返回 png。

我使用最新版本的 seleniumphantomjsnodejs

所以我的问题是如何通过 GhostDriver 访问 PhantomJS 网页实例并评估 render 方法?

最佳答案

有一种特殊的方法可以从 GhostDriver 执行 PhantomJS 脚本,使用下一个命令:

POST /session/id/phantom/execute

它包含在 GhostDriver v1.1.0 中, 所以它应该从 PhantomJS v.1.9.6 开始工作.

看这个例子:

def execute(script, args):
driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://stackoverflow.com')

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test.pdf")'''
execute(render, [])

注意在 OS X PhantomJS renders web page as images由于 OS X 中 Qt 渲染引擎的限制(至少对于 PhantomJS v.1.9.8 及更早版本),无法选择文本。

关于python - 如何通过 GhostDriver (selenium) 使用 PhantomJS 运行网页代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23125557/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com