如何使用python从页面下载文件

2024-04-29 09:10:12 发布

您现在位置:Python中文网/ 问答频道 /正文

从这个页面下载txt文件时遇到问题:https://www.ceps.cz/en/all-data#RegulationEnergy(向下滚动并看到下载:txt、xls和xml)。在

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

我不确定如何解决的主要问题:

  • 文件没有一个真正的链接,我可以调用并下载它,但链接是用JS根据过滤器和文件类型创建的。

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

尝试的方法:

  • 使用诸如ParseHub这样的scraper来下载链接并没有按预期工作。但这个铲运机是最接近我想要的。

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

如果您能为这项任务提出一些解决方案,请提前谢谢。:-)


Tags: 文件httpstxtdata链接wwwcz页面
2条回答

您可以使用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()

你应该这样做:

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)

相关问题 更多 >