python - 无法使用 os.path.join() 踢出 os.chdir() 以存储下载的文件
问题描述
我已经结合 selenium 在 python 中编写了一个脚本来从网页下载几个文件。我利用点击指向.docx
文件的链接来下载它们。下载文件后,它们会以一些愚蠢的前缀重命名。我的脚本可以完美地完成这一切。
要将下载的文件存储在文件夹中,我使用os.chdir()
了我想替换为os.path.join()
. 但是,这就是我卡住的地方,无法找到关于如何使用它的任何想法。一旦我能os.path.join()
以正确的方式使用,我就可以重命名下载的文件。
为了下载和重命名文件,我该如何使用os.path.join()
而不是在这种情况下?os.chdir()
到目前为止,我已经写过:
import time
import os
from selenium import webdriver
link = 'https://www.online-convert.com/file-format/doc'
desk_location = r'C:\Users\WCS\Desktop\file_container'
if not os.path.exists(desk_location):os.mkdir(desk_location)
os.chdir(desk_location) #I wish to kick out this line to replace with os.path.join() somewhere within the script
def download_files(url):
driver.get(url)
for item in driver.find_elements_by_css_selector("a[href$='.doc']")[:2]:
filename = item.get_attribute("href").split("/")[-1]
item.click()
time_to_wait = 10
time_counter = 0
try:
while not os.path.exists(filename):
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
os.rename(filename,"its_"+filename) #It's a silly renaming in order to check whether this line is working
except Exception:pass
if __name__ == '__main__':
chromeOptions = webdriver.ChromeOptions()
prefs = {'download.default_directory' : desk_location,
'profile.default_content_setting_values.automatic_downloads': 1
}
chromeOptions.add_experimental_option('prefs', prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
download_files(link)
driver.quit()
解决方案
为了使脚本使用os.path.join()
而不是os.chdir()
我需要更改脚本中的几行。感谢@John Gordon 在评论中提出的建议。
整改部分:
def download_files(url):
driver.get(url)
for item in driver.find_elements_by_css_selector("a[href$='.doc']")[:2]:
filename = item.get_attribute("href").split("/")[-1]
#Define the path in the following line in order to resuse later
file_location = os.path.join(desk_location, filename)
item.click()
time_to_wait = 10
time_counter = 0
try:
while not os.path.exists(file_location): #use the file_location here
time.sleep(1)
time_counter += 1
if time_counter > time_to_wait:break
#Now rename the file once it is downloaded
os.rename(file_location, os.path.join(desk_location, "its_"+filename))
except Exception:pass
推荐阅读
- java - 为什么?完全 gc 发生在两次次要 gc 之前?
- xamarin - DeviceInformation.FindAllAsync 找不到相同数量的 COM 端口
- c# - 使用授权服务器的 REST API 到 API 身份验证
- python - numpy: linspace 计算生成 nan。如何从两个数组中删除点对?
- assembly - 减少时 DAW 不工作 - 组装
- sql - Oracle 中的 XML 类型
- javascript - jQuery:如何获取表格单元格数据并将其附加到输入字段?
- ruby - 如何在ruby中获得一个短的第n个素数代码
- java - 如果我们用 AES 密钥包装 256 位 AES 密钥,那么包装密钥的大小可以超过 32 个字节?
- xaml - 在这种情况下,哪种布局最合适?Xamarin 形式