【问题标题】:Selenium :: Python :: Chrome ExtensionSelenium :: Python :: Chrome 扩展
【发布时间】:2017-03-07 11:04:28
【问题描述】:

我正在尝试用Selenium WebDriver 加载google chrome extension

但我收到错误OSError: Path to the extension doesn't exist

这是我正在使用的代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from os import path

path = "path to chrome driver"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_extension('Adblock-Plus_v1.12.4_0.crx') # ALTERNATIVE 0
driver = webdriver.Chrome(path, chrome_options=chrome_options)

在阅读了本网站上的各种类似问题后,我尝试了以下两种选择:

# Alternative 1
chrome_options.add_extension('~/Library/Application\ Support/Google/Chrome/Default/Extensions/[Extension ID]/Adblock-Plus_v1.12.4_0.crx')

#Alternative 2
chrome_options.add_extension(path.abspath("Adblock-Plus_v1.12.4_0.crx"))

但它们都不起作用。备选方案 1 给出与原始代码相同的错误消息,而备选方案 2 给出错误 AttributeError: 'str' object has no attribute 'abspath'

有人知道我可以做些什么不同的事情吗?

【问题讨论】:

  • 你试过driver = webdriver.Chrome(chrome_options=chrome_options) 吗?它对我有用。
  • 感谢您的回复。是的,这就是我在代码的最后一行所做的……不是吗?
  • 不,您包含路径。您还要导入路径然后覆盖它。
  • 好的,明白你的意思。试过了,但我确实收到了同样的错误消息OSError: Path to the extension doesn't exist
  • 您是否安装了 Chrome 的网络驱动程序?你可以在这里找到它。 sites.google.com/a/chromium.org/chromedriver/downloads

标签: python google-chrome selenium


【解决方案1】:

可能更感谢,这是因为 python 引用了错误的路径,路径中通常是 ~/ 的主目录快捷方式。 Python 将尝试从当前目录运行该文件,例如,如果您的代码在 ~/Dev/testproject 中,而上面调用的代码实际上是在尝试运行 /home/username/Dev/testproject/~/Library/Application Support/Google/Chrome/Default/Extensions/[Extension ID]/Adblock-Plus_v1.12.4_0.crx

尝试使用以下方法:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import os

chromedriver = "path to chrome driver"
chrome_options = webdriver.ChromeOptions()


# choose one of the following 2:
chrome_options.add_extension(os.path.expanduser('~/Library/Application\ Support/Google/Chrome/Default/Extensions/[Extension ID]/Adblock-Plus_v1.12.4_0.crx'))  # Option 1: if your extension is not also in your project folder
chrome_options.add_extension(os.path.abspath('Adblock-Plus_v1.12.4_0.crx'))  # Option 2: if your extension IS in your project folder


driver = webdriver.Chrome(chromedriver, chrome_options=chrome_options)

编辑:避免声明名为 path 的变量,因为您正在从 os 导入 path。这就是为什么您在备选方案 #2 上遇到错误的原因。

【讨论】:

  • 谢谢,钩叶。它现在正在工作。关于path....我自己可以看到这个。有时我只是在调试时看不到明显的东西;-)
猜你喜欢
  • 2020-05-14
  • 1970-01-01
  • 2016-03-17
  • 2014-07-12
  • 2019-02-08
  • 2013-05-06
  • 2021-12-12
  • 1970-01-01
  • 2011-06-30
相关资源
最近更新 更多