有没有办法在 Python 中使用 PhantomJS?
- 2024-12-30 08:42:00
- admin 原创
- 95
问题描述:
我想在Python中使用PhantomJS。我在 Google 上搜索了这个问题,但找不到合适的解决方案。
我发现os.popen()
这可能是一个不错的选择。但我无法向它传递一些参数。
目前使用subprocess.Popen()
可能是一个合适的解决方案。我想知道是否有更好的解决方案。
有没有办法在 Python 中使用 PhantomJS?
解决方案 1:
在 Python 中使用 PhantomJS 最简单的方法是通过 Selenium。最简单的安装方法是
安装NodeJS
使用 Node 的包管理器安装 phantomjs:
npm -g install phantomjs-prebuilt
安装 selenium (在你的虚拟环境中,如果你正在使用它)
安装后,您可以像下面一样轻松地使用 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')
参考:
如何在 python webdriver 中为 phantomjs/ghostdriver 设置代理?
解决方案 2:
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
解决方案 3:
现在,由于 GhostDriver 与 PhantomJS 捆绑在一起,通过 Selenium 使用它变得更加方便。
我尝试了 Pykler 建议的 PhantomJS 的 Node 安装,但实际使用中发现它比 PhantomJS 的独立安装慢。我猜独立安装之前没有提供这些功能,但从 v1.9 开始,它确实提供了这些功能。
安装 PhantomJS(http://phantomjs.org/download.html)(如果你使用的是 Linux,以下说明将有所帮助https://stackoverflow.com/a/14267295/382630)
使用 pip 安装 Selenium。
现在你可以像这样使用
import selenium.webdriver
driver = selenium.webdriver.PhantomJS()
driver.get('http://google.com')
# do some processing
driver.quit()
解决方案 4:
以下是我使用 PhantomJS 和 Django 测试 JavaScript 的方法:
移动/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);
});
移动/测试.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
解决方案 5:
@Pykler 的答案很棒,但 Node 要求已经过时了。该答案中的评论建议使用更简单的答案,我将其放在这里以节省其他人的时间:
安装 PhantomJS
正如@Vivin-Paliath 指出的那样,它是一个独立项目,而不是 Node 的一部分。
苹果:
brew install phantomjs
乌本图:
sudo apt-get install phantomjs
ETC
设置
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()
解决方案 6:
这是我做的,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(" Exception: %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')
解决方案 7:
如果使用 Anaconda,请使用以下命令安装:
conda install PhantomJS
在你的脚本中:
from selenium import webdriver
driver=webdriver.PhantomJS()
完美运行。
解决方案 8:
如果您使用Buildout ,您可以轻松地使用gp.recipe.node配方自动化 Pykler 描述的安装过程。
[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs
该部分将 node.js 安装为二进制文件(至少在我的系统上),然后使用 npm 安装 PhantomJS。最后,它创建一个入口点bin/phantomjs
,您可以使用它调用 PhantomJS webdriver。(要安装 Selenium,您需要在 egg 要求或 Buildout 配置中指定它。)
driver = webdriver.PhantomJS('bin/phantomjs')