如何在使用bs4浏览文件的href后下载文件。获取href没有问题,但是当我尝试获取文件时,会出现错误
以下是我从中获取href的源HTML:
<a href="/census-recensement/2016/dp-pd/prof/details/download-
telecharger/comp/GetFile.cfm?Lang=E&FILETYPE=CSV&GEONO=059"
title="Canada, provinces and territories – File format CSV" class="btn
btn-default btn-block"></a>
第一次尝试:不起作用
for i, r in enumerate(rows):
file = f'{r.find("th").text}.csv'
urlretrieve(f'https://{r.find("a")["href"]}', filename=str(filename.joinpath(file)))
第二次尝试:它也不起作用
for i, r in enumerate(rows):
href = r.find('a', href=True)
remote_file = requests.get(href['href'])
with open(href['href'], 'wb') as f:
for chunk in remote_file.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
href['href']
将返回/census-recensement/2016/dp-pd/prof/details/download-telecharger/comp/GetFile.cfm?Lang=E&FILETYPE=CSV&GEONO=059
您必须在此之前添加https://www12.statcan.gc.ca
要保存文件,请尝试以下操作
要解决您的问题,您可以添加'https://www12.statcan.gc.ca'前缀为href。之后,您将获得文件的有效链接。对于示例中的文件,指向文件的有效链接为'https://www12.statcan.gc.ca/census-recensement/2016/dp-pd/prof/details/download-telecharger/comp/GetFile.cfm?Lang=E&FILETYPE=CSV&;Geno=059'。如果您在网站上有可单击按钮,可以下载一些文件,您可以右键单击->;复制链接位置并将其粘贴到记事本或其他文本编辑器,然后查看此链接以查找href的前缀
相关问题 更多 >
编程相关推荐