使用Requests库下载XLSB文件返回400 Bad Request导致文件损坏的问题求助
Fix for 400 Bad Request & Corrupted XLSB File Download
The 400 Bad Request error and corrupted file issue you’re facing is almost certainly due to the server rejecting your request—most likely because your script isn’t sending the HTTP headers that the server expects from a legitimate client (like a web browser). Many servers block requests that don’t include a proper User-Agent string, flagging them as bot traffic.
Here’s how to resolve this:
Key Fixes to Apply
- Add Browser-like Headers: Include a
User-Agent(and optionally anAcceptheader) to mimic a real browser request. - Validate Response Status: Always check if the request succeeded before writing content to a file—this prevents saving error pages as your XLSB file.
Corrected Code
import requests url = 'http://rigcount.bakerhughes.com/static-files/55ff50da-ac65-410d-924c-fe45b23db298' file_name = r'local path with xlsb extension' # Headers to mimic a Chrome browser request headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36', 'Accept': 'application/vnd.ms-excel.sheet.binary.macroEnabled.12, */*' } try: # Send request with headers response = requests.get(url, headers=headers) # Raise an error if request failed (4xx/5xx status codes) response.raise_for_status() # Write the valid content to file only if request succeeded with open(file_name, "wb") as file: file.write(response.content) print(f"File downloaded successfully! Check {file_name}") except requests.exceptions.RequestException as e: print(f"Download failed: {e}")
Additional Verification Steps
- After running the code, print
response.status_codeto confirm it returns200(OK). - Check
response.headers['Content-Type']—it should showapplication/vnd.ms-excel.sheet.binary.macroEnabled.12(the correct MIME type for XLSB files) if the download worked.
By adding these headers and validating the response, you’ll get the actual XLSB file instead of a corrupted error page.
内容的提问来源于stack exchange,提问作者baharak Al
相关产品推荐
相关产品推荐

