硒打开本地文件
问题内容:
我正在尝试使用Firefox /
Selenium实例作为图像的基本幻灯片。我的想法是,我将打开本地目录中的webdriver
和driver.get()
文件。
运行以下命令时,出现错误消息: selenium.common.exceptions.WebDriverException: Message: Tried to run command without establishing a connection
我的假设是selenium正在尝试测试下一个driver.get()
请求,并且不允许本地非Web连接的连接,有没有办法绕过此行为?我的代码示例如下所示:
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)
一如既往,任何帮助将不胜感激。
更新:我应该补充说,相同的基本脚本结构适用于网站-我可以遍历多个网站而没有任何错误。
问题答案:
我认为您只需要添加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()