· Charlotte Will · webscraping · 5 min read
How to Scrape PDFs from Website Pages with Python
How to scrape PDFs from website pages with Python: BeautifulSoup and Selenium fetch the pages, and a Python PDF library extracts the text.

Introduction
Finding a PDF link on a page is the easy part. Once the file is on disk, the work starts. A PDF is a fixed-layout format, and the words you want sit inside positioning instructions rather than in a readable sequence, so pulling clean text out of one takes a parser built for the format.
This guide covers both halves of the job in Python: locating the documents, then extracting their contents.
Finding the PDF Links
When you scrape PDFs from website pages, start by listing every candidate link rather than downloading on sight. That keeps a single malformed URL from ending the run and gives you a chance to see what the page actually holds before you commit bandwidth.
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
BASE_URL = 'https://example.com/documents'
response = requests.get(BASE_URL, headers={'User-Agent': 'Mozilla/5.0'}, timeout=30)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
pdf_links = set()
for anchor in soup.find_all('a', href=True):
href = urljoin(BASE_URL, anchor['href'])
if href.lower().endswith('.pdf'):
pdf_links.add(href)
for link in sorted(pdf_links):
print(link)
urljoin matters here. Most sites link to documents with a relative path such as /files/2024-report.pdf, and a relative href is useless as a download target until it is resolved against the page it came from. If the page carries its links in a JSON payload instead of in the markup, the same idea applies to that payload. The metadata extraction guide covers the other structured sources a page exposes alongside its visible content.
Pages That Load Their Links With JavaScript
Some sites build their document list in the browser, which means the HTML served by requests has no links in it at all. Selenium runs the page and hands back the rendered DOM, which is where the <a> elements actually exist.
from selenium import webdriver
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('--headless=new')
driver = webdriver.Chrome(options=options)
try:
driver.get(BASE_URL)
for element in driver.find_elements(By.CSS_SELECTOR, 'a[href$=".pdf"]'):
print(element.get_attribute('href'))
finally:
driver.quit()
Selenium is slow next to a plain HTTP request, so reach for it only when the static HTML turns out to be empty. Running a real browser for every page on a site you visit hundreds of times is a poor trade.
Downloading the Files
import os
import requests
def download_pdf(url, dest_dir='downloads'):
os.makedirs(dest_dir, exist_ok=True)
filename = url.rsplit('/', 1)[-1] or 'document.pdf'
path = os.path.join(dest_dir, filename)
with requests.get(url, stream=True, timeout=60) as response:
response.raise_for_status()
content_type = response.headers.get('Content-Type', '')
if 'application/pdf' not in content_type:
raise ValueError(f'expected a PDF at {url}, got {content_type}')
with open(path, 'wb') as handle:
for chunk in response.iter_content(chunk_size=8192):
handle.write(chunk)
return path
Checking Content-Type before writing catches the case where a PDF link points at a login page or a captcha wall, and the file you saved is HTML.
Extracting Text with pypdf
pypdf reads the content stream of each page and reconstructs the text from it.
from pypdf import PdfReader
reader = PdfReader(path)
text = '\n\n'.join(page.extract_text() or '' for page in reader.pages)
A scanned document has no text stream to reconstruct, so extract_text() returns an empty string. That is a property of the file, not a bug in your code, and OCR is the only way through it.
Extracting Tables with pdfplumber
When the document is mostly tables, pdfplumber does a better job because it understands the ruled lines and cell boundaries.
import pdfplumber
with pdfplumber.open(path) as pdf:
for number, page in enumerate(pdf.pages, start=1):
for table in page.extract_tables():
print(f'--- page {number} ---')
for row in table:
print(row)
Putting It Together
import os
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
from pypdf import PdfReader
BASE_URL = 'https://example.com/documents'
OUT_DIR = 'downloads'
os.makedirs(OUT_DIR, exist_ok=True)
response = requests.get(BASE_URL, headers={'User-Agent': 'Mozilla/5.0'}, timeout=30)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
for anchor in soup.find_all('a', href=True):
url = urljoin(BASE_URL, anchor['href'])
if not url.lower().endswith('.pdf'):
continue
path = os.path.join(OUT_DIR, url.rsplit('/', 1)[-1])
with requests.get(url, stream=True, timeout=60) as pdf_response:
pdf_response.raise_for_status()
with open(path, 'wb') as handle:
for chunk in pdf_response.iter_content(chunk_size=8192):
handle.write(chunk)
reader = PdfReader(path)
text = '\n\n'.join(page.extract_text() or '' for page in reader.pages)
print(f'{path}: {len(text)} characters')
Practical Tips
- Check
robots.txtand the terms of the site before you automate anything against it. - Send a real
User-Agentso the operator of the site knows who is calling. - Pause between requests. A short delay keeps you under most rate limits.
- Keep the PDF next to the extracted text, so a parsing change does not mean downloading everything again.
- Extract the text once and store it. Re-parsing on every read is wasted work.
- Check whether the site exposes a JSON or REST endpoint before scraping pages at all. Where an API exists, an API call in Python is cheaper and more reliable than parsing rendered HTML.
Conclusion
A PDF scraping job splits cleanly into finding the documents and reading them, and neither half needs anything exotic. BeautifulSoup or Selenium gets you the URLs, requests gets you the bytes, and pypdf or pdfplumber turns those bytes into text you can search. The failure modes worth knowing about are the ones above: relative links, pages that render their content in JavaScript, links that return HTML instead of a document, and scanned files with no text layer at all.
FAQs
How do I extract text from a PDF in Python? Open the file with
PdfReaderfrompypdfand callextract_text()on each page. Join the results with blank lines so paragraph breaks survive the move into your own data.Can Selenium download PDF files? It can, though you rarely want it to. Selenium is for pages that build their content in the browser. Once you have a direct PDF URL, a plain
requestscall is faster and lighter.Why is the extracted text empty or out of order? An empty result usually means the PDF is a scan with no text layer, which needs OCR. Out-of-order text usually means the page uses multi-column layout, and
pdfplumberhandles columns better thanpypdfdoes.Should I use pypdf or pdfplumber?
pypdfis the lighter of the two and handles text extraction well.pdfplumberearns its extra dependency when the documents contain tables, because it returns cell structure instead of a wall of text.How do I find PDF links that a page loads with JavaScript? Fetch the page with
requestsfirst and check whether any PDF links appear in the HTML. If none do, load the same URL in Selenium and collect the rendered anchors instead.



