Programming

파이썬에서 PhantomJS를 사용하는 방법이 있습니까?

procodes 2020. 5. 7. 21:25
반응형

파이썬에서 PhantomJS를 사용하는 방법이 있습니까?


Python 에서 PhantomJS 를 사용하고 싶습니다 . 이 문제를 봤지만 적절한 해결책을 찾지 못했습니다.

내가 찾을 수 os.popen()있는 좋은 선택이 될 수 있습니다. 그러나 나는 그것에 대한 몇 가지 주장을 전달할 수 없었습니다.

지금 사용 subprocess.Popen()하는 것이 적절한 해결책 일 수 있습니다. 더 나은 솔루션이 있는지 여부를 알고 싶습니다.

파이썬에서 PhantomJS를 사용하는 방법이 있습니까?


파이썬에서 PhantomJS를 사용하는 가장 쉬운 방법은 Selenium을 이용하는 것입니다. 가장 간단한 설치 방법은

  1. NodeJS 설치
  2. Node의 패키지 관리자를 사용하여 phantomjs를 설치하십시오. npm -g install phantomjs-prebuilt
  3. 셀레늄 설치 (가상 환경에서 사용하는 경우)

설치 후 팬텀을 다음과 같이 간단하게 사용할 수 있습니다.

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')

참고 문헌 :


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

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()

PhantomJS와 Django를 사용하여 자바 스크립트를 테스트하는 방법은 다음과 같습니다.

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);
});

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

테스트 실행 :

manage.py test mobile


The answer by @Pykler is great but the Node requirement is outdated. The comments in that answer suggest the simpler answer, which I've put here to save others time:

  1. Install PhantomJS

    As @Vivin-Paliath points out, it's a standalone project, not part of Node.

    Mac:

    brew install phantomjs
    

    Ubuntu:

    sudo apt-get install phantomjs
    

    etc

  2. Set up a virtualenv (if you haven't already):

    virtualenv mypy  # doesn't have to be "mypy". Can be anything.
    . mypy/bin/activate
    

    If your machine has both Python 2 and 3 you may need run virtualenv-3.6 mypy or similar.

  3. Install selenium:

    pip install selenium
    
  4. Try a simple test, like this borrowed from the docs:

    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()
    

this is what I do, python3.3. I was processing huge lists of sites, so failing on the timeout was vital for the job to run through the entire list.

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')

If using Anaconda, install with:

conda install PhantomJS

in your script:

from selenium import webdriver
driver=webdriver.PhantomJS()

works perfectly.


In case you are using Buildout, you can easily automate the installation processes that Pykler describes using the gp.recipe.node recipe.

[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs

That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point bin/phantomjs, which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)

driver = webdriver.PhantomJS('bin/phantomjs')

참고URL : https://stackoverflow.com/questions/13287490/is-there-a-way-to-use-phantomjs-in-python

반응형