print('Hello world!')
셀레늄을 사용하여 Chrome에서 파일을 다운로드하려고합니다. 파일을 다운로드 할 때마다 'TCBT'로 시작하지만 나머지 파일 이름은 매번 달라집니다. 그 파일 하나만 다운로드하고 싶습니다.
파일을 다운로드하기 위해 마지막 클릭을 눌렀을 때 흥미로운 일이 발생합니다. 웹 사이트가 더 느리고 파일이 더 커져서 다운로드를 클릭하면 결정 불가능한 시간 (20-60 초)이 걸립니다. 그런 다음 10-30 초가 더 걸리는 파일 다운로드를 시작하는 팝업 창이 나타납니다.
파일 다운로드가 완료되는시기를 식별하기 위해 여러 가지 무한 루프를 시도했지만 항상 루프에 갇히거나 건너 뜁니다. 내가 원하는 것을 찾기 위해 glob을 사용할 수 있기 때문에 파일 이름과 관련이 있다고 생각합니다. 몇 가지 예를 참조하십시오.
한 번의 시도 :
while True:
download_folder = os.path.expanduser('~')+'/Downloads/'
filenames = glob.glob(download_folder+'TCBT*')
for name in filenames:
if name.endswith('.crdownload'):
time.sleep(1)
if name.endswith('.xls'):
break
else:
continue
이것은 무슨 일이 있어도 계속 반복됩니다. 처음 20-60 초 동안 (팝업이 다운로드를 시작하기를 기다리는 동안) 파일이 없기 때문에 "계속"부분을 사용하여 돌아가서 파일 이름을 얻으려고합니다.
또한 온라인에서 찾은 기능을 사용해 보았습니다.
def download_wait(directory, timeout, nfiles=None):
"""
Wait for downloads to finish with a specified timeout.
Args
----
directory : str
The path to the folder where the files will be downloaded.
timeout : int
How many seconds to wait until timing out.
nfiles : int, defaults to None
If provided, also wait for the expected number of files.
"""
seconds = 0
dl_wait = True
while dl_wait and seconds < timeout:
time.sleep(1)
dl_wait = False
files = os.listdir(directory)
if nfiles and len(files) != nfiles:
dl_wait = True
for fname in files:
if fname.endswith('.crdownload'):
dl_wait = True
seconds += 1
return seconds
download_wait(download_folder, 30)
이것을 사용하면 아무 일도 일어나지 않고 스크립트가 완료됩니다. 나는 그것이 파일을 보지 않고 (다운로드를 시작하는 데 20-60 초가 걸리기 때문에) 폴더를 확인하고 완료한다고 가정하고 있습니다.
이 문제를 해결하는 방법에 대한 의견이 있습니까?
여기에 내가 해결 한 방법이 있습니다. 두 번째 루프에서 벗어나려면 두 번째 휴식을 추가해야했습니다. 트리에 몇 가지 추가 :
# Wait for download
while True:
download_folder = os.path.expanduser('~')+'/Downloads/'
filenames = glob.glob(download_folder+'TCBT*')
if len(filenames) > 0 and not any('.crdownload' in name for name in filenames):
break
for name in filenames:
if name.endswith('.crdownload'):
continue
if name.endswith('.xls'):
print('')
print('Download complete.')
print('')
break
else:
break
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다