用于保存多个链接列表中的http响应的Python脚本

问题描述 投票:0回答:1

你好,我有一个网址列表

示例: 网址1 网址2 网址

我想创建一个 python 脚本,其中包含请求标头(例如令牌)以保存来自文本文件中的网址列表的响应。

请帮我完成这项任务。

我手动尝试过,但我有很多网址列表。我想自动执行此操作。 请帮忙

python http httprequest httpresponse
1个回答
0
投票

我希望这有帮助。

import requests

header = {'Authorization': 'token_here'}
urls = ["https://url1", "https://url2", "https//:url3"]
for index, url in enumerate(urls):
    try:
        response = requests.get(url=url, headers=header)
        if response.status_code == 200:
            with open(f'response_{index}.text', 'w') as file:
                file.write(response.text)
            print(f'Saved response from {url} to response_{index}.txt')
        else:
            print(f'Error: Unable to fetch from {url}. Status code: {response.status_code}')

    except Exception as e:
        print(f'Error: Unable to fetch from {url}. Exception: {str(e)}')
© www.soinside.com 2019 - 2024. All rights reserved.