Python,PhantomJS 说我没有使用无头?

Posted

技术标签:

【中文标题】Python,PhantomJS 说我没有使用无头?【英文标题】:Python, PhantomJS says I am not using headless? 【发布时间】:2018-10-29 04:52:32 【问题描述】:

我的代码是:

from selenium import webdriver

driver = webdriver.PhantomJS(executable_path='driver/bin/phantomjs.exe')
driver.get("https://www.test.com")
print(driver.current_url)

它似乎运行良好,但在它运行之前我总是得到这个错误:

UserWarning: Selenium 对 PhantomJS 的支持已被弃用,请使用无头版本的 Chrome 或 Firefox 代替 warnings.warn('Selenium 对 PhantomJS 的支持已被弃用,请使用无头版本

为什么会出现此错误?我以为我的 PhantomJS 是无头的,因为它仍然可以工作并且没有浏览器弹出窗口,这个错误保存可以忽略吗?

【问题讨论】:

PhantomJS 基于旧版本的 webkit,不再维护。 groups.google.com/forum/#!topic/phantomjs/9aI5d-LDuNE 好吧,@generalhenry 有没有一种简单的方法可以让 Chrome 或 Firefox 无头? intoli.com/blog/running-selenium-with-headless-chrome short version install chrome, chromedriver 然后在你的代码调用driver = webdriver.Chrome . . . 和你的代码的其余部分应该正常运行。 或***.com/questions/46753393/… for firefox 但 PhontomJS 仍然更快,并且需要大型 carawling 项目。 【参考方案1】:

Selenium 认为 PhantomJS 已弃用,因此您需要 Chrome 或 Firefox 处于无头模式。

以下是在无头模式下使用 Chrome 的步骤:

    从https://sites.google.com/a/chromium.org/chromedriver/getting-started下载chrome驱动 解压到文件夹中 将此文件夹添加到您的PATH environment variable(如果您不这样做,则必须在下面的代码中使用webdriver.Chrome('/your/path/to/chromedriver') 而不是webdriver.Chrome())

然后像这样使用它:

from selenium import webdriver

# prepare the option for the chrome driver
options = webdriver.ChromeOptions()
options.add_argument('headless')

# start chrome browser
browser = webdriver.Chrome(chrome_options=options)
browser.get('http://www.google.com/xhtml')
print(browser.current_url)
browser.quit()

更多关于how to use ChromeDriver 对于其他选项:here(也可以是 here 和 here)

【讨论】:

这个方法现在似乎也被弃用了。我试过了,它说:DeprecationWarning: use options instead of chrome_options browser = webdriver.Chrome(chrome_options=options) @RyanHart,您的 ChromeDriver 和 selenium 版本是多少?我有 ChromeDriver 84.0.4147.30 和 selenium 3.141.0(我刚刚更新了它们)。我刚刚检查了答案中的代码,没有任何错误。如果您仍然遇到错误,请尝试 browser = webdriver.Chrome(options=options) 而不是 browser = webdriver.Chrome(chrome_options=options),如果您仍然遇到错误,请告诉我 我也安装了那些确切的版本,但它仍然给我那个弃用警告。但是,我确实通过删除options 行以及webdriver.Chrome() 中的所有参数来使其工作。所以,我不需要任何帮助。也许您的设置中以某种方式抑制了此类警告。我不知道。不过,现在一切都很好。 哦,你是对的。 options=options 修复了弃用警告消息。当我早些时候尝试时,我什至还没有编写任何脚本,所以我看到的只是警告消息,并假设它不起作用。我决定再次修改它,因为我决定要禁用所有图像和 javascript 以加快我的脚本。【参考方案2】:

在 Selenium 3.8.1 PhantomJS 中标记为已弃用的 webdriver,建议我们在无头模式下使用 Chrome 或 Firefox。

【讨论】:

【参考方案3】:

你可以用这个:

from selenium import webdriver

browser = webdriver.Chrome('chromedriver_path/chromedriver')
browser.get("https://www.test.com")
print(browser.current_url)
browser.quit()

【讨论】:

【参考方案4】:

找到一个替代方案,您可以将 options.add_argument('headless') 添加到 chrome

【讨论】:

以上是关于Python,PhantomJS 说我没有使用无头?的主要内容,如果未能解决你的问题,请参考以下文章

运用 phantomjs 无头浏览器破解四种反爬虫技术

无头浏览器

在 Selenium 版本 3.7.0 无头驱动程序 phantomjs 版本 2.1 上启用 Cookie

如何使用phantomjs无头浏览器处理selenium中的警报

无头浏览器是啥?它有啥用?

python Selenium 网页自动化