使用 Python 從 PDF 中提取超連結


使用 Python 從 PDF 中提取超連結可以透過使用多個庫來完成,例如 **PyPDF2**、**PDFMiner** 和 **pdfx** 等。

  • PyPDF2:Python 內建庫,充當 PDF 工具包,允許我們讀取和操作 PDF 檔案。

  • PDFMiner:用於從 PDF 文件中提取資訊的工具,它完全專注於獲取和分析文字資料。

  • Pdfx:此模組用於從給定的 PDF 中提取元資料、純資料和 URL。

使用 PyPDF2

PyPDF2 主要能夠提取資料、合併 PDF、拆分和旋轉頁面。此方法包括讀取 PDF 檔案並將其轉換為文字,然後使用正則表示式從文字中提取 URL。

安裝 PyPDF2

要使用此 PyPDF2 庫,我們必須使用以下程式碼進行安裝。

pip install PyPDF2

讀取 PDF 檔案

以下程式碼將在 二進位制模式 ('rb') 中開啟 PDF 檔案並建立一個檔案物件,然後將其傳遞給 PyPDF2.PdfFileReader 以建立一個 pdfReader 物件,該物件與 PDF 內部的內容進行互動。

pdfReader.numPages 將定義 PDF 中的頁面數,而 extractText() 方法將透過迭代每個頁面來提取文字。

import PyPDF2
 
file = "Enter PDF File Name" 
pdfFileObject = open(file, 'rb')  
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)  
for page_number in range(pdfReader.numPages):
     
    pageObject = pdfReader.getPage(page_number)
    pdf_text = pageObject.extractText()
    print(pdf_text)
     
pdfFileObject.close()

用於查詢 URL 的正則表示式

正則表示式 (regex) 方法用於在文字中搜索特定的模式,例如 URL。在以下程式碼中,findall() 方法將搜尋從 PDF 頁面提取的文字,並返回包含 URL 的列表。r"(https?://\S+)" 將查詢以 http://https:// 開頭的字串。

# Import Module
import PyPDF2
import re 
 
# Enter File Name
file = "Enter PDF File Name"
 
# Open File file
pdfFileObject = open(file, 'rb')
  
pdfReader = PyPDF2.PdfFileReader(pdfFileObject)
 
# Regular Expression (Get URL from String)
def Find(string): 
   
    # findall() has been used 
    # with valid conditions for urls in string 
    regex = r"(https?://\S+)"
    url = re.findall(regex,string)
    return [x for x in url] 
   
# Iterate through all pages
for page_number in range(pdfReader.numPages):
     
    pageObject = pdfReader.getPage(page_number)
     
    # Extract text from page
    pdf_text = pageObject.extractText()
     
    # Print all URL
    print(Find(pdf_text))
     
# CLose the PDF 
pdfFileObject.close() 

Test.pdf


輸出

['http://www.education.gov.yk.ca/']

使用 pdfx

pdfx 模組專門用於從給定的 PDF 檔案中提取 URL、元資料和純文字。與 PyPDF2 相比,此方法使提取 URL 的過程更簡單。

安裝 pdfx

使用“pip install pdfx”安裝它。

pip install pdfx

示例

在以下程式碼中,pdfx.PDFx() 讀取給定的 PDF 檔案,而 references_as_dict() 方法將返回一個包含在 PDF 檔案中找到的 URL 的字典。

# Import Module
import pdfx 
 
# Read PDF File
pdf = pdfx.PDFx("File Name") 
 
# Get list of URL
print(pdf.get_references_as_dict())

輸出

{'url':['http://www.education.gov.yk.ca/']}

使用 PDFMiner

與 pyPDF 工具相比,PDFMiner 是功能更強大且更復雜的庫。它允許我們詳細提取文字、超連結以及 PDF 檔案的結構。它透過將整個檔案轉換為元素樹結構來讀取 PDF。

安裝 PDFMiner

要使用 PDFMiner 庫,您首先需要使用以下命令安裝它。

pip install pdfminer.six

示例

以下示例程式碼定義了使用 PDFMiner 逐頁讀取 PDF,將其轉換為文字以提取超連結。extract_pages() 函式處理給定的 PDF 檔案並返回佈局物件,而 LTLink 物件用於識別 PDF 檔案中的超連結。

from pdfminer.high_level import extract_pages
from pdfminer.layout import LTTextContainer, LTAnno, LTLink

file = "Enter PDF File Name"

# Iterate through PDF pages
for page_layout in extract_pages(file):
    for element in page_layout:
        if isinstance(element, LTTextContainer):
            # Extracting text
            for text_line in element:
                if isinstance(text_line, LTAnno):
                    continue
                print(text_line.get_text())
        if isinstance(element, LTLink):
            # Extracting hyperlinks
            print(f"Found hyperlink: {element.get('uri')}")

輸出

Found hyperlink: http://www.education.gov.yk.ca/

更新於:2024-09-17

4K+ 瀏覽量

啟動您的 職業生涯

透過完成課程獲得認證

開始
廣告