首页 > 解决方案 > Selenium - 使用 chromedriver 通过导航栏运行 javascript

问题描述

我一直在尝试使用 Selenium 将 javascript 插入 Chrome 导航栏,但没有任何成功。

goto = "javascript:gotoText(-884)"<br />
browser.get(goto)

手动完成时(通过单击并将“javascript:gotoText(-884)”写入导航栏)它就像一个魅力。但是,硒给我带来了这个错误。有什么解决方法吗?该网页本身没有提供任何可点击的内容来直接指向此链接。

感谢您的任何建议!

---------------------------------------------------------------------------
WebDriverException                        Traceback (most recent call last)
<ipython-input-297-41c52a12ba91> in <module>()
----> 1 browser.get(asd)

/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py in get(self, url)
    331         Loads a web page in the current browser session.
    332         """
--> 333         self.execute(Command.GET, {'url': url})
    334 
    335     @property

/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py in execute(self, driver_command, params)
    319         response = self.command_executor.execute(driver_command, params)
    320         if response:
--> 321             self.error_handler.check_response(response)
    322             response['value'] = self._unwrap_value(
    323                 response.get('value', None))

/anaconda3/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py in check_response(self, response)
    240                 alert_text = value['alert'].get('text')
    241             raise exception_class(message, screen, stacktrace, alert_text)
--> 242         raise exception_class(message, screen, stacktrace)
    243 
    244     def _value_or_default(self, obj, key, default):

WebDriverException: Message: unknown error: unsupported protocol
  (Session info: chrome=71.0.3578.98)
  (Driver info: chromedriver=2.45.615355 (d5698f682d8b2742017df6c81e0bd8e6a3063189),platform=Mac OS X 10.13.6 x86_64)

标签: pythonseleniumweb-scrapingselenium-chromedriver

解决方案


就像 Moshe Slavin 提到的那样,您需要传递有效的 URL,否则您将收到此错误:

WebDriverException: Message: unknown error: unsupported protocol

如果您想使用 JavaScript 传递一些有效的 URL,例如

http://www.google.com

然后你可以使用 window.location.replace() 像下面的 JavaScriptExecutor 在 selenium 和 python,它的行为与 driver.get() 方法相同:

from selenium import webdriver
driver = webdriver.Chrome('C:\\NotBackedUp\\chromedriver.exe')
driver.execute_script("window.location.replace('http://www.google.com');")

有关更多信息,请参阅以下链接:

将javascript插入URL的方法?


推荐阅读