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

fly*_*yer 202 python phantomjs

我想在Python中使用PhantomJS.我搜索了这个问题,但找不到合适的解决方案.

我发现os.popen() 可能是个不错的选择.但我无法传递一些论据.

使用subprocess.Popen()可能是目前适当的解决方案.我想知道是否有更好的解决方案.

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

Pyk*_*ler 371

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

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

安装后,您可以使用幻像,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

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

driver = webdriver.PhantomJS() # or add to your PATH
Run Code Online (Sandbox Code Playgroud)

......以下内容:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
Run Code Online (Sandbox Code Playgroud)

参考文献:

  • 这很好用,也许可以节省我几天的时间.谢谢.如果想要将整个渲染页面作为源返回,那就是`driver.page_source`. (40认同)
  • 我同意ghost有疯狂的依赖关系,即使在安装了数百万个X11相关库之后,我实际上也无法启动并运行它.幽灵是一个恐怖的故事. (8认同)
  • @phabtar你需要将路径传递给phantomjs作为PhantomJS的第一个参数...或修复你的windows syspath以便能够看到phantomjs. (5认同)
  • 这确实很好用,我很惊喜,因为http://phantomjs.org/faq.html说"不是Node.js模块" - 在https://npmjs.org/package/phantomjs上的npm包装器使它表现为这个目的.在我的情况下,我想这样做:`bodyStr = driver.find_element_by_tag_name("body").get_attribute("innerHTML")`和......它工作了! (4认同)
  • 愚蠢的问题:为什么我必须安装node-js?有没有其他办法获得pahantomJs? (2认同)
  • @Pykler PhantomJS**不是**在节点中编写的.它是用C++编写的,是一个无头webkit浏览器.节点包只安装适当的二进制文件. (2认同)
  • 在Windows下,我没有必要通过`node`和`npm`安装`phantomJS`.从http://phantomjs.org/download.html下载二进制文件并将`phantomjs.exe`放入我的PATH中的某个位置(例如`c:\ Windows\System32`),反之亦然(将它放在任何地方并添加文件夹到PATH)足以使它在Python中工作. (2认同)

Mar*_*ers 80

PhantomJS最近完全放弃了Python支持.但是,PhantomJS现在嵌入了Ghost Driver.

自那以后,一个新项目加紧填补空白:ghost.py.您可能想要使用它:

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
Run Code Online (Sandbox Code Playgroud)

  • 即使支持被删除,我发现安装npm(节点包管理器)并使用它来安装最新的phantomjs(具有webdriver支持)并在python中安装selenium ...比试图让PyQT或PySide正常工作更容易.幻影有什么好处它真正无头,并且不需要UI/X11相关的库来工作. (21认同)
  • 在尝试使用ghost.py并讨厌我的生活后,我在下面添加了一个答案,解释了我的首选解决方案 (12认同)
  • Pykler的"讨厌我的生活"并不是轻描淡写.如果有人将此问题的"正确答案"更改为Pykler's,我本可以节省一天的努力. (8认同)
  • 在今天早上尝试了一系列不同的方法之后,@Pykler解决方案最终得到了最顺利的解决方案. (3认同)
  • @YPCrumble:不幸的是,只有OP可以做到这一点; 改变接受的答案. (2认同)

Pan*_*aj 40

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

我按照Pykler的建议尝试了PhantomJS的Node安装,但实际上我发现它比PhantomJS的独立安装慢.我想独立安装没有提前提供这些功能,但从v1.9开始,它就是这样做的.

  1. 安装PhantomJS(http://phantomjs.org/download.html)(如果你在Linux上,以下说明将有助于/sf/answers/998710681/)
  2. 使用pip安装Selenium.

现在你可以像这样使用

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

driver.quit()
Run Code Online (Sandbox Code Playgroud)

  • 特别感谢指出关于在Ubuntu上安装PhantomJS的SO答案,它帮助了我. (3认同)

Emi*_*röm 8

以下是我使用PhantomJS和Django测试javascript的方法:

mobile/test_no_js_errors.js:

var page = require('webpage').create(),
    system = require('system'),
    url = system.args[1],
    status_code;

page.onError = function (msg, trace) {
    console.log(msg);
    trace.forEach(function(item) {
        console.log('  ', item.file, ':', item.line);
    });
};

page.onResourceReceived = function(resource) {
    if (resource.url == url) {
        status_code = resource.status;
    }
};

page.open(url, function (status) {
    if (status == "fail" || status_code != 200) {
        console.log("Error: " + status_code + " for url: " + url);
        phantom.exit(1);
    }
    phantom.exit(0);
});
Run Code Online (Sandbox Code Playgroud)

mobile/tests.py:

import subprocess
from django.test import LiveServerTestCase

class MobileTest(LiveServerTestCase):
    def test_mobile_js(self):
        args = ["phantomjs", "mobile/test_no_js_errors.js", self.live_server_url]
        result = subprocess.check_output(args)
        self.assertEqual(result, "")  # No result means no error
Run Code Online (Sandbox Code Playgroud)

运行测试:

manage.py test mobile


And*_*w E 6

@Pykler答案很棒,但Node要求已经过时了.该答案中的评论提出了更简单的答案,我在这里为了节省其他时间而放在这里:

  1. 安装PhantomJS

    正如@ Vivin-Paliath指出的那样,它是一个独立的项目,而不是Node的一部分.

    苹果电脑:

    brew install phantomjs
    
    Run Code Online (Sandbox Code Playgroud)

    Ubuntu的:

    sudo apt-get install phantomjs
    
    Run Code Online (Sandbox Code Playgroud)

    等等

  2. 设置一个virtualenv(如果你还没有):

    virtualenv mypy  # doesn't have to be "mypy". Can be anything.
    . mypy/bin/activate
    
    Run Code Online (Sandbox Code Playgroud)

    如果您的机器同时具有Python 2和3,则可能需要运行virtualenv-3.6 mypy或类似.

  3. 安装硒:

    pip install selenium
    
    Run Code Online (Sandbox Code Playgroud)
  4. 尝试一个简单的测试,就像借用文档一样:

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.PhantomJS()
    driver.get("http://www.python.org")
    assert "Python" in driver.title
    elem = driver.find_element_by_name("q")
    elem.clear()
    elem.send_keys("pycon")
    elem.send_keys(Keys.RETURN)
    assert "No results found." not in driver.page_source
    driver.close()
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

这就是我所做的,python3.3.我正在处理庞大的站点列表,因此在超时失败对于完成整个列表的工作至关重要.

command = "phantomjs --ignore-ssl-errors=true "+<your js file for phantom>
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)

# make sure phantomjs has time to download/process the page
# but if we get nothing after 30 sec, just move on
try:
    output, errors = process.communicate(timeout=30)
except Exception as e:
    print("\t\tException: %s" % e)
    process.kill()

# output will be weird, decode to utf-8 to save heartache
phantom_output = ''
for out_line in output.splitlines():
    phantom_output += out_line.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)


clg*_*lg4 5

如果使用Anaconda,请安装:

conda install PhantomJS
Run Code Online (Sandbox Code Playgroud)

在您的脚本中:

from selenium import webdriver
driver=webdriver.PhantomJS()
Run Code Online (Sandbox Code Playgroud)

完美地工作。