【问题标题】:How can we download multiple Excel files from a URL?我们如何从一个 URL 下载多个 Excel 文件?
【发布时间】:2022-01-16 04:17:34
【问题描述】:

我正在尝试从 URL beloe 下载所有 Excel 文件。

https://healthcare.ascension.org/price-transparency/price-transparency-files

这是我的 hacky 代码。

from bs4 import BeautifulSoup
import urllib.request


for numb in ('1', '10'):
    resp = urllib.request.urlopen("https://healthcare.ascension.org/price-transparency/price-transparency-files")
    soup = BeautifulSoup(resp, from_encoding=resp.info().get_param('charset'))

    for link in soup.find_all('a', href=True):
        if 'xls' in link['href']:
            print(link['href'])
            dls = link['href']
            urllib.request.urlretrieve(dls, str(numb) + ".xls")

根据我刚刚进行的一些 Google 搜索,我只是将其汇总在一起。当我运行该代码时,我得到了这个错误。

ValueError: unknown url type: '/-/media/project/ascension/healthcare/price-transparency-files/al/630578923_ascension-saint-vincents-east_standardcharges.xlsx'

我刚刚循环了 1:10,因为我不确定如何获取 Excel 文件的实际名称,但是查看页面后面显示 Excel URL 看起来像这样。

每个 Excel 文件都有一个名为“标准费用”的工作表。我不确定是否必须下载每个文件,或者只是打开它并从名为“标准费用”的工作表中复制数据,但基本上我试图将“标准费用”中的所有内容放入一个数据框中。当我查看一些表格时,我可以很快看出标题有时会略有不同,但我认为'pd.concat' 应该能够非常无缝地处理这个问题。知道如何将所有内容放入一个数据框中吗?谢谢。

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    使用User-Agent获取成功的请求,您可以在网络调用中找到

    import requests
    from bs4 import BeautifulSoup
    headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36"}
    resp = requests.get("https://healthcare.ascension.org/price-transparency/price-transparency-files",headers=headers)
    soup = BeautifulSoup(resp.text,"html.parser")
    

    写入 Excel 文件的代码:

    for link in soup.find_all('a', href=True):
        if 'xls' in link['href']:
            url="https://healthcare.ascension.org"+link['href']
            file="tmp/"+url.split("/")[-1].split(".")[0]+".xls"
            print(file)
            urllib.request.urlretrieve(url, file)  
        
    

    这里的 URL 将只包含最后一部分,因此您必须与基本 URL 连接才能调用在本地下载 Excel 文件

    输出:

    【讨论】:

    • 我认为这很接近了!它下载了近 120 个 Excel 文件,但每当我尝试打开其中一个文件时,我都会收到一条错误消息,内容为“文件和扩展名 .xls 不匹配。该文件可能已损坏或不安全。此外,所有文件都没有数据;所有的大小都是 0KB。在您的屏幕截图中,我看到了相同的 0KB。想法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多