Selenium Python -循环每次都变慢



我正在尝试从"汽车"列表中自动下载文件。然后将文件保存在我的电脑上,解压缩并以汽车的名称重新命名。

问题是,我的forloop越来越慢。第一个循环大约需要1秒来执行,但是第10个循环几乎需要1分钟。

谁能检查一下我的代码并指出潜在的缺陷?我用的是chromedriver
for car in carList:
try:
#Apre il filter
filter = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), "filter")]'))
)    
filter.click()

#Find car
n_sport = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '#door'))
)
n_sport.send_keys(car)
n_sport.send_keys(Keys.ENTER)

#open_car = driver.find_element_by_xpath("//a[contains(@title," + "0" +car +")]")
open_car = WebDriverWait(driver, 30).until(
EC.element_to_be_clickable((By.XPATH, "//a[contains(@title," + "0" +car +")]")
))
open_car.click()

##driver.execute_script("arguments[0].click();", checkbox_elem)                

#open file system
fs = WebDriverWait(driver, 30).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), "file system")]'))
)
fs.click()


#open C:

c = WebDriverWait(driver, 60).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), "C:")]'))
)
c.click()


#Right click on file:

f = WebDriverWait(driver, 60).until(
EC.element_to_be_clickable((By.XPATH, textToSearch))
)

ActionChains(driver).context_click(f).perform()



#Save

save = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(@href, "#GETFILE")]'))
)

save.click()

#Find empty button:
empty = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), "Svuota elenco")]'))
)

#Empty
empty.click()

print('The file has been downloaded from the car: ' + car )

if doesZipExists:
renameFile(parentFolder, ext, car, fname)

except:
print('Error: car ' + car + ' has not been found')

这可能是你有东西留在内存中没有被清除,你总是可以手动清除内存在finally块:

for car in carList:
try:
#Apre il filter
filter = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, '//*[contains(text(), "filter")]'))
)    
...
if doesZipExists:
renameFile(parentFolder, ext, car, fname)

except:
print('Error: car ' + car + ' has not been found')
finally:
del filter,
del n_sport, 
del open_car,
del fs, 
del c, 
del f, 
del save, 
del empty

我也会避免使用python关键字(例如filter)作为变量名,因为你可能会陷入各种各样的问题。

还有一个我看不到的因素,你所做的renameFile(parentFolder, ext, car, fname)调用,所以这可能也会给你带来麻烦,特别是考虑到这看起来像一个IO操作。

相关内容

  • 没有找到相关文章

最新更新