![](/img/trans.png)
[英]Take screenshot of webelement in Selenium Python and save file
[英]Selenium after take screenshot unlink txt file
我在一個文件夾中有一些 txt 文件,我列出了目錄和鏈接。 使用 selenium 訪問鏈接后,我截取了屏幕截圖。 現在我正在嘗試刪除此鏈接txt文件。
下面的代碼我試過
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
import os
path = "E:/xampp/htdocs/spool/"
directories = os.listdir(path)
for dir in directories:
# print(dir)
files = os.listdir(path+dir)
for file in files:
# print(path+dir+'/'+file)
f = open(path+dir+'/'+file, "r")
list = f.read()
data = list.split("||")
print(data[1])
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get(data[1])
driver.save_screenshot(data[0]+'.png')
driver.close()
os.unlink(f.name)
問題是取消鏈接時間它給出了以下錯誤
Traceback (most recent call last):
File "index.py", line 21, in <module>
os.unlink(f.name)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'E:/xampp/htdocs/spool/7/2020-09-1112.txt'
我也使用過os.close(3)
,之后出現錯誤“
list = f.read()
OSError: [Errno 9] Bad file descriptor
" 截屏后如何取消鏈接?
Version python : Python 3.8.4
如您所見,另一個進程正在使用 txt 文件。
我認為這就是問題所在; 你打開了文件但沒有關閉它。
我建議您訪問https://www.tutorialspoint.com/python/file_close.htm
嘗試調用f.close()
然后取消鏈接。
這種文件處理方法並不完全安全。 如果在對文件執行某些操作時發生異常,代碼將退出而不關閉文件。
在您的情況下,您忘記關閉文件。
f.close()
我建議使用這種方法來避免這種情況
with open("test.txt", mode= 'r', encoding = 'utf-8') as f:
# perform file operations
pass
# we dont need to explicitly close() the method, it is done internally.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.