有没有办法在Python中使用PhantomJS?

2024-04-19 11:40:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Python中使用PhantomJS。我在谷歌上搜索了这个问题,但找不到合适的解决方法。

我发现os.popen()可能是个不错的选择。但我不能给它一些理由。

现在使用subprocess.Popen()可能是一个合适的解决方案。我想知道是否有更好的解决办法。

有没有办法在Python中使用PhantomJS?


Tags: 方法osphantomjs解决方案subprocesspopen理由办法
3条回答

幽灵最近总共dropped Python support。然而,PhantomJS现在嵌入了Ghost Driver

此后,一个新的项目开始填补空白:^{}。你可能想用它来代替:

from ghost import Ghost
ghost = Ghost()

with ghost.start() as session:
    page, extra_resources = ghost.open("http://jeanphi.me")
    assert page.http_status==200 and 'jeanphix' in ghost.content

在python中使用PhantomJS最简单的方法是通过Selenium。最简单的安装方法是

  1. 安装NodeJS
  2. 使用节点的包管理器安装phantomjs:npm -g install phantomjs-prebuilt
  3. 安装selenium(在您的virtualenv中,如果您正在使用它的话)

安装后,您可以使用phantom,其简单方法如下:

from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

如果未正确设置系统路径环境变量,则需要将确切的路径指定为webdriver.PhantomJS()的参数。替换为:

driver = webdriver.PhantomJS() # or add to your PATH

。。。包括以下内容:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

参考文献:

现在,由于GhostDriver与PhantomJS捆绑在一起,通过Selenium使用它变得更加方便。

我按照Pykler的建议尝试了PhantomJS的节点安装,但是在实践中我发现它比PhantomJS的独立安装慢。我想独立安装之前并没有提供这些功能,但是到了v1.9,它已经提供了很多功能。

  1. 安装PhantomJS(http://phantomjs.org/download.html)(如果您在Linux上,以下说明将有助于https://stackoverflow.com/a/14267295/382630
  2. 使用pip安装Selenium。

现在你可以这样用了

import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing

driver.quit()

相关问题 更多 >