Python:将 Excel 文件原样保存到文件夹
Python: Save Excel File As-Is To Folder
我正在使用 beautifulsoup4 从网站下载 Excel 文件。
我只需要下载文件。我不需要重命名它们,只需将它们下载到一个文件夹,相对于代码所在的位置。
函数接收 beautifulsoup 调用,搜索 <a>
然后调用链接。
def save_excel_files(sfile):
print("starting")
for link in sfile.find_all("a"):
candidate_link = link.get("href")
if (candidate_link is not None
and "Flat.File" in candidate_link):
xfile = requests.get(candidate_link)
if xfile:
### I just don't know what to do...
我试过使用 os.path
; with open("xtest", "wb") as f:
和许多其他变体。在这里呆了两个晚上,完全卡住了。
第一个问题是我什至无法下载文件并将其保存在任何地方。 xfile
解析为 [response 200]
,所以这部分工作正常,我只是很难编码实际的下载和保存。
像这样的东西应该有用:
xfile = requests.get(candidate_link)
file_name = candidate_link.split('/')[-1]
if xfile:
with open(file_name, "wb") as f:
f.write(xfile.content)
测试了以下 link 我在 google 中随机发现:
candidate_link = "http://berkeleycollege.edu/browser_check/samples/excel.xls"
我正在使用 beautifulsoup4 从网站下载 Excel 文件。
我只需要下载文件。我不需要重命名它们,只需将它们下载到一个文件夹,相对于代码所在的位置。
函数接收 beautifulsoup 调用,搜索 <a>
然后调用链接。
def save_excel_files(sfile):
print("starting")
for link in sfile.find_all("a"):
candidate_link = link.get("href")
if (candidate_link is not None
and "Flat.File" in candidate_link):
xfile = requests.get(candidate_link)
if xfile:
### I just don't know what to do...
我试过使用 os.path
; with open("xtest", "wb") as f:
和许多其他变体。在这里呆了两个晚上,完全卡住了。
第一个问题是我什至无法下载文件并将其保存在任何地方。 xfile
解析为 [response 200]
,所以这部分工作正常,我只是很难编码实际的下载和保存。
像这样的东西应该有用:
xfile = requests.get(candidate_link)
file_name = candidate_link.split('/')[-1]
if xfile:
with open(file_name, "wb") as f:
f.write(xfile.content)
测试了以下 link 我在 google 中随机发现:
candidate_link = "http://berkeleycollege.edu/browser_check/samples/excel.xls"