Python 에서 PhantomJS 를 사용하고 싶습니다 . 이 문제를 봤지만 적절한 해결책을 찾지 못했습니다.
내가 찾을 수 os.popen() 있는 좋은 선택이 될 수 있습니다. 그러나 나는 그것에 대한 몇 가지 주장을 전달할 수 없었습니다.
지금 사용 subprocess.Popen()하는 것이 적절한 해결책 일 수 있습니다. 더 나은 솔루션이 있는지 여부를 알고 싶습니다.
파이썬에서 PhantomJS를 사용하는 방법이 있습니까?
Python 에서 PhantomJS 를 사용하고 싶습니다 . 이 문제를 봤지만 적절한 해결책을 찾지 못했습니다.
내가 찾을 수 os.popen() 있는 좋은 선택이 될 수 있습니다. 그러나 나는 그것에 대한 몇 가지 주장을 전달할 수 없었습니다.
지금 사용 subprocess.Popen()하는 것이 적절한 해결책 일 수 있습니다. 더 나은 솔루션이 있는지 여부를 알고 싶습니다.
파이썬에서 PhantomJS를 사용하는 방법이 있습니까?
답변:
파이썬에서 PhantomJS를 사용하는 가장 쉬운 방법은 Selenium을 이용하는 것입니다. 가장 간단한 설치 방법은
npm -g install phantomjs-prebuilt설치 후 팬텀을 다음과 같이 간단하게 사용할 수 있습니다.
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')
참고 문헌 :
driver.page_source입니다.
bodyStr= driver.find_element_by_tag_name("body").get_attribute("innerHTML")
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부터는 많은 기능을 제공합니다.
이제 이렇게 사용할 수 있습니다
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
@Pykler 의 답변 은 훌륭하지만 노드 요구 사항은 오래되었습니다. 이 답변의 의견은 더 간단한 답변을 제안하며, 다른 사람들의 시간을 절약하기 위해 여기에 넣었습니다.
PhantomJS 설치
@ Vivin-Paliath가 지적했듯이, 그것은 Node의 일부가 아닌 독립형 프로젝트입니다.
맥:
brew install phantomjs
우분투 :
sudo apt-get install phantomjs
기타
virtualenv(아직 설정 하지 않은 경우) 설정 :
virtualenv mypy # doesn't have to be "mypy". Can be anything.
. mypy/bin/activate
컴퓨터에 Python 2와 3이 모두 있으면 실행 virtualenv-3.6 mypy또는 유사 해야 할 수도 있습니다 .
셀레늄 설치 :
pip install selenium문서 에서 빌린 다음과 같은 간단한 테스트를 시도하십시오 .
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()PhantomJSWindows 에 설치하는 방법 ? pip명령을 사용하여 작동하지 않는 것 같습니다 .
이것이 내가하는 일입니다 .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')
Anaconda를 사용하는 경우 다음을 설치하십시오.
conda install PhantomJS
스크립트에서 :
from selenium import webdriver
driver=webdriver.PhantomJS()
완벽하게 작동합니다.
당신이 사용하는 경우 Buildout을 쉽게 Pykler을 사용하여 설명하는 설치 프로세스를 자동화 할 수 있습니다 gp.recipe.node의 조리법을.
[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs
이 부분은 node.js를 바이너리 (적어도 내 시스템에서는)로 설치 한 다음 npm을 사용하여 PhantomJS를 설치합니다. 마지막으로 bin/phantomjsPhantomJS 웹 드라이버를 호출 할 수 있는 진입 점을 만듭니다 . Selenium을 설치하려면 계란 요구 사항 또는 빌드 아웃 구성에서 Selenium을 지정해야합니다.
driver = webdriver.PhantomJS('bin/phantomjs')
gp.recipe.phantomjs, 즉를 구성 phantomjs하고casperjs
subprocess.popen하지만 api를 원활하게하기위한 확장 기능이 있습니다.