我有一个下载链接,但是当使用python requests.get模块时,它不下载任何东西

62lalag4  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(107)

我有下面的代码,但是当我运行它时,它在终端中保持加载,没有显示错误或检索任何数据。我想这可能是联系。如何获取在浏览器上使用链接时出现的XML文件?

import requests

def download_xml_file(url, save_path):
    try:
        response = requests.get(url)
        response.raise_for_status()  # Check if the request was successful
        with open(save_path, 'wb') as file:
            file.write(response.content)
        print(f"XML file downloaded successfully and saved at: {save_path}")
    except requests.exceptions.RequestException as e:
        print(f"Error downloading XML file: {e}")

url = 'https://apps.fcc.gov/eas/GetEntityDownload.xml?type=G'
save_path = 'path/to/destination/file.xml'  # Specify the location where you want to save the downloaded file

download_xml_file(url, save_path)

字符串
我试图运行代码,希望得到的文件附加到链接,但字面上的终端没有显示任何东西,它只是继续运行脚本。

d4so4syb

d4so4syb1#

服务器由于某种原因不喜欢你的头文件,所以不回答你的请求,显然它会更好地响应403或其他东西。
我尝试了下面的代码,它工作得很好,因为添加了头。你可以添加自己的头或使用这个头(它的旧)。
最重要的是“用户代理”

import requests

url = "https://apps.fcc.gov/eas/GetEntityDownload.xml?type=G"

payload = {}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36', "Upgrade-Insecure-Requests": "1","DNT": "1","Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Language": "en-US,en;q=0.5","Accept-Encoding": "gzip, deflate"}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

字符串

相关问题