債券系SEの苦悩

SIer所属 8年目SEの備忘

MENU

【IT】Python 特定サイトのPDFを一括ダウンロードする

import requests
import os
from bs4 import BeautifulSoup

# PDFを保存するフォルダのパス
pdf_folder_path = './pdf_folder'

# PDFを保存するフォルダが存在しなければ作成する
if not os.path.exists(pdf_folder_path):
    os.makedirs(pdf_folder_path)

# 特定のサイトのURL
url = 'https://example.com'

# サイトにアクセスして、HTMLを取得する
response = requests.get(url)
html = response.content

# HTMLをパースして、BeautifulSoupオブジェクトを作成する
soup = BeautifulSoup(html, 'html.parser')

# リンクを取得する
links = soup.find_all('a')

# PDFファイルのリンクを保存するためのリストを初期化する
pdf_links = []

# リンクの中から、PDFファイルへのリンクを抽出する
for link in links:
    href = link.get('href')
    if href.endswith('.pdf'):
        pdf_links.append(href)

# PDFファイルをダウンロードする
for link in pdf_links:
    response = requests.get(link)
    file_name = link.split('/')[-1]
    file_path = os.path.join(pdf_folder_path, file_name)
    with open(file_path, 'wb') as f:
        f.write(response.content)