Автоматизируйте извлечение документов с сайтаPython

Программы на Python
Ответить
Anonymous
 Автоматизируйте извлечение документов с сайта

Сообщение Anonymous »

Я новичок в Python и пытаюсь извлечь документы с веб-сайтов.
  • Я пытаюсь автоматизировать извлечение документа ( «информационный бюллетень фонда») с веб-сайтов. Я хочу, чтобы моя программа (а) зашла на веб-сайт, (б) выполнила поиск по слову/ссылке «информационный бюллетень / информационный бюллетень», (в) ввела ссылку, (г) загрузила PDF-файл на свой рабочий стол.
  • Мой набор данных представляет собой файл Excel с тремя столбцами. Столбец A — «fund_name», столбец B — «url_website», а столбец C — «factsheet_url_pattern».
    Изображение набора данных
  • "website_url" — это когда нет прямой ссылки на документ. «factsheet_url_pattern» — это когда есть прямая ссылка на документ
  • Предположим, первый веб-сайт: https://globalfunds.virtus.com /products/virtus-gf-us-small-cap-focus-fund#shareclass.I/ period.quarterly
  • Программа успешно открывается ссылку на информационный бюллетень, но не удается сохранить ее в формате PDF на рабочем столе
6. ПРОБЛЕМА: на данном этапе у меня открыта ссылка, но я не могу скачать файл в формате PDF. «Это ошибка: не удалось загрузить https://globalfunds.virtus.com/assets/f ... t_1116.pdf: контент не является файлом PDF (тип контента: text/html; charset=utf-8) "
Спасибо!
При попытке извлечь информационный бюллетень возникает ошибка:
Не удалось загрузить https://globalfunds.virtus.com/assets/f ... t_1116.pdf: контент не является файлом PDF (тип контента: text/html; charset=utf-8)
import pandas as pd
import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import re # For sanitizing file names
import numpy as np # For handling NaN values

def download_file(url, file_path):
try:
# Send an HTTP GET request to the URL with headers
headers = {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
)
}
response = requests.get(url, stream=True, headers=headers, allow_redirects=True)
print(f"HTTP Status Code: {response.status_code}")
print(f"Final URL after redirects: {response.url}")
response.raise_for_status() # Check if the request was successful

# Check if the content type is PDF
content_type = response.headers.get('Content-Type', '').lower()
print(f"Content-Type: {content_type}")
if 'pdf' not in content_type:
print(f"Failed to download {url}: Content is not a PDF file (Content-Type: {content_type})")
return False

# Write the content to a file in chunks
with open(file_path, 'wb') as file:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
file.write(chunk)
print(f"File downloaded successfully and saved to: {file_path}")
return True
except Exception as e:
print(f"An error occurred: {e}")
return False

def find_factsheet_link(website_url):
try:
headers = {
'User-Agent': (
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
)
}
response = requests.get(website_url, headers=headers)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
keywords = ['factsheet', 'fact sheet'] # Updated keywords list

# Find all links on the page
for a in soup.find_all('a', href=True):
href = a['href']
text = a.get_text()

# Check if any keyword is in the href or the text of the link
if any(keyword.lower() in href.lower() or keyword.lower() in text.lower() for keyword in keywords):
# Build the full URL
if not href.startswith('http'):
href = urljoin(website_url, href)

# Only consider URLs that end with .pdf
if href.lower().endswith('.pdf'):
return href
print(f"Could not find a PDF factsheet link on {website_url}")
return None
except Exception as e:
print(f"Error accessing {website_url}: {e}")
return None

def main():
# Use a fixed download folder
download_folder = 'Factsheets'
if not os.path.exists(download_folder):
os.makedirs(download_folder)

# Read funds from Excel file
df = pd.read_excel('funds.xlsx')

# Replace NaN values with empty strings
df = df.replace({np.nan: ''})

funds = df.to_dict('records')

for fund in funds:
# Extract and sanitize fund data
fund_name = str(fund.get('fund_name', '')).strip()
website_url = str(fund.get('website_url', '')).strip()
factsheet_url_pattern = str(fund.get('factsheet_url_pattern', '')).strip()

# Check if fund_name and website_url are not empty
if not fund_name or not website_url:
print(f"Missing fund_name or website_url for fund: {fund}")
continue

print(f"\nProcessing {fund_name}")

if factsheet_url_pattern and factsheet_url_pattern.lower() != 'nan':
# Use the provided factsheet URL
factsheet_url = factsheet_url_pattern
else:
# Try to find the factsheet link
factsheet_url = find_factsheet_link(website_url)
if not factsheet_url:
print(f"Could not find factsheet link for {fund_name}")
continue

# Print the factsheet URL being used
print(f"Factsheet URL for {fund_name}: {factsheet_url}")

# Download the file
file_extension = os.path.splitext(factsheet_url)[1]
if not file_extension:
file_extension = '.pdf' # Default to .pdf
file_name = f"{fund_name}{file_extension}"
# Sanitize the file name to remove any illegal characters
sanitized_file_name = re.sub(r'[\\/*?:"|]', "", file_name)
file_path = os.path.join(download_folder, sanitized_file_name)
success = download_file(factsheet_url, file_path)
if success:
print(f"Downloaded {sanitized_file_name}")
else:
print(f"Failed to download factsheet for {fund_name}")

if __name__ == '__main__':
main()



Подробнее здесь: https://stackoverflow.com/questions/791 ... om-website
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

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