【问题标题】:How to download file from a page using python如何使用python从页面下载文件
【发布时间】:2019-02-09 17:51:48
【问题描述】:

我无法从此页面下载 txt 文件:https://www.ceps.cz/en/all-data#RegulationEnergy(当您向下滚动并查看下载:txt、xls 和 xml)。

我的目标是创建将转到链接页面的抓取工具,例如单击 txt 链接并保存下载的文件。

我不知道如何解决的主要问题:

  • 该文件没有我可以调用和下载的真实链接,但该链接是使用 JS 基于过滤器和文件类型创建的。

  • 当我使用 Python 的 requests 库并调用带有所有标头的链接时,它只会将我重定向到 https://www.ceps.cz/en/all-data

尝试的方法:

  • 使用 ParseHub 等抓取工具下载链接未按预期工作。但这个刮刀是最接近我想要得到的。

  • 使用 requests 库使用 HXR 请求用于下载文件的标头连接到链接,但它只是将我重定向到 https://www.ceps.cz/en/all-data

如果您可以为此任务提出一些解决方案,请提前感谢您。 :-)

【问题讨论】:

    标签: python selenium web-scraping python-requests


    【解决方案1】:

    您可以使用 Selenium 将此数据下载到您选择的目录;您只需要指定将保存数据的目录。在下文中,我会将 txt 数据保存到我的桌面:

    from selenium import webdriver
    
    download_dir = '/Users/doug/Desktop/'
    
    chrome_options = webdriver.ChromeOptions()
    prefs = {'download.default_directory' : download_dir}
    chrome_options.add_experimental_option('prefs', prefs)
    driver = webdriver.Chrome(chrome_options=chrome_options)
    driver.get('https://www.ceps.cz/en/all-data')
    
    container = driver.find_element_by_class_name('download-graph-data')
    button = container.find_element_by_tag_name('li')
    button.click()
    

    【讨论】:

    • 嗨@duhaime 很好的解决方案,你能告诉我通过 selenium 读取 html 内容的方法吗?
    • @NagaKiran 当然,使用上面的代码,我们会调用driver.page_source - 这将返回当前页面的 HTML。我希望这会有所帮助!
    【解决方案2】:

    你应该这样做:

    import requests
    
    txt_format = 'txt'
    xls_format = 'xls' # open in binary mode
    xml_format = 'xlm' # open in binary mode
    
    def download(file_type):
        url = f'https://www.ceps.cz/download-data/?format={txt_format}'
    
        response = requests.get(url)
    
        if file_type is txt_format:
            with open(f'file.{file_type}', 'w') as file:
                file.write(response.text)
        else:
            with open(f'file.{file_type}', 'wb') as file:
                file.write(response.content)
    
    download(txt_format)
    

    【讨论】:

    • 你应该以wb模式打开文件并写response.content
    • 既然他要下载一个txt文件,而response.text是str类型,最好在'w' 模式
    • 但是对于 xls 和 xml 文件?
    • 在这种情况下是'wb'模式。我添加这些变量只是为了让他知道如何实现它。但是,我会编辑答案谢谢!
    猜你喜欢
    • 1970-01-01
    • 2017-04-09
    • 1970-01-01
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多