Selenium 打开本地文件

Dan*_*iel 3 python selenium

我正在尝试使用 Firefox/Selenium 实例作为图像的基本幻灯片。这个想法是我将从本地目录中打开一个webdriverdriver.get()文件。

当我运行以下命令时,我收到一个错误: selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection

我的假设是 selenium 正在尝试测试下一个driver.get()请求并且不允许本地的、非网络连接的连接有没有办法绕过这种行为?我的代码示例如下所示:

from selenium import webdriver
import time
from os import listdir
from selenium.common.exceptions import WebDriverException

driver = webdriver.Firefox()

image_source = '/home/pi/Desktop/slideshow/photo_frames/daniel/images/'

for file in listdir(image_source):
    if file.endswith('jpg'):
        file_name = image_source + file
        driver.get(file_name)
        time.sleep(5)
Run Code Online (Sandbox Code Playgroud)

与往常一样,任何帮助将不胜感激。

更新:我应该补充一点,相同的基本脚本结构适用于网站 - 我可以循环浏览多个网站而不会出现任何错误。

Lev*_*ker 8

我认为您只需要添加file://到文件名中即可。这对我有用:

from selenium import webdriver
import time
from os import listdir
from selenium.common.exceptions import WebDriverException

def main():
    image_source = '/home/pi/Desktop/slideshow/photo_frames/daniel/images/'

    driver = webdriver.Firefox()

    try:
        for file in listdir(image_source):
            if file.endswith('jpg'):
                file_name = 'file://' + image_source + file
                driver.get(file_name)
                time.sleep(5)
    finally:
        driver.quit()

if __name__ == "__main__":
    main()
Run Code Online (Sandbox Code Playgroud)

  • 以上不适用于本地 html。如果我用本地 html 尝试这个,代码就会卡住。 (3认同)

adr*_*nbd 6

如果您像我一样来到这里希望 Selenium 为您的本地 html 文件提供服务,那么上述接受的答案需要稍作修改才能工作,正如Niklas Rosencrantz所注意到的。

要让 Selenium 在您的浏览器中提供本地 html,并假设文件在您当前的工作目录中,请尝试此操作(我在 Windows 上,使用 Selenium 3.141.0 和 Python 3.7 - 如果对您很重要):

from selenium import webdriver
import os

browser = webdriver.Firefox()
html_file = os.getcwd() + "//" + "relative//path//to//file.html"
browser.get("file:///" + html_file)
Run Code Online (Sandbox Code Playgroud)


Dan*_*ord 5

这也可以用 Pathlib 来完成

from selenium import webdriver
from pathlib import Path

browser = webdriver.Firefox()
html_file = Path.cwd() / "relative//path//to//file.html"
browser.get(html_file.as_uri())
Run Code Online (Sandbox Code Playgroud)

如果您是 pathlib 的新手,那么 / 语法可能看起来有点奇怪,但它非常易于使用,这里有一个很好的教程https://realpython.com/python-pathlib/