PDF. документы, загруженные с помощью Python, не открываютсяPython

Программы на Python
Anonymous
PDF. документы, загруженные с помощью Python, не открываются

Сообщение Anonymous »

Я использовал следующий код для загрузки нескольких PDF-файлов с общедоступного сайта в соответствии с их идентификационными номерами, которые указаны в файле Excel. Сначала это работает, но файлы не открываются в Adobe Reader, Chrome или Edge.

Код: Выделить всё

import pandas as pd
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# Disable insecure certificate warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# Load the list of numbers from Excel
df = pd.read_excel('prospectos_numero.xlsx')
# Setting the header
headers = {'User-Agent': 'Mozilla/5.0'}

# Click on each number in the list and download the corresponding document
for number in df['ID_num']:  # Replace 'numbers' with the name of the column in your Excel file
url = f'https://fnet.bmfbovespa.com.br/fnet/publico/downloadDocumento?id={number}'
response = requests.get(url, headers=headers, verify=False)

if response.status_code == 200 and response.headers['Content-Type'] == 'application/pdf':
with open(f'{number}.pdf', 'wb') as file:
file.write(response.content)
print(f'Document {number} downloaded with success.')
else:
print(f'Failed to download {number}. Status code: {response.status_code}, Type of content: {response.headers["Content-Type"]}')
Я пробовал использовать модуль base64, но проблема не устранена:

Код: Выделить всё

import base64
import pandas as pd
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning

# Disable insecure certificate warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# Load the list of numbers from Excel
df = pd.read_excel('prospectos_numero.xlsx')
# Setting the header
headers = {'User-Agent': 'Mozilla/5.0'}

# Click on each number in the list and download the corresponding document
for number in df['ID_num']:  # Replace 'ID_num' with the name of the column in your Excel file
url = f'https://fnet.bmfbovespa.com.br/fnet/publico/downloadDocumento?id={number}'
response = requests.get(url, headers=headers, verify=False)

if 'Content-Disposition' in response.headers:
print('Content-Disposition:', response.headers['Content-Disposition'])
filename = response.headers['Content-Disposition'].split('filename=')[-1].strip('"')
print('filename:', filename)

content = base64.b64decode(response.content)

if response.status_code == 200 and response.headers['Content-Type'] == 'application/pdf':
with open(f'{number}.pdf', 'wb') as file:
file.write(response.content)
print(f'Document {number} downloaded with success.')
else:
print(f'Failed to download {number}. Status code: {response.status_code}, Type of content: {response.headers["Content-Type"]}')
В Adobe Reader отображается ошибка: «Adobe Acrobat Reader не удалось открыть файл «1514.pdf», поскольку этот тип файла не поддерживается или он поврежден». Повреждает ли код файлы, и я могу это исправить?

Подробнее здесь: https://stackoverflow.com/questions/790 ... -wont-open

Вернуться в «Python»