我想从PDF文件中提取文本,这是在一个网站。该网站包含PDF文档的链接,但当我单击该链接时,它会自动下载该文件。是否可以在不下载文本的情况下从该文件提取文本
import fitz # this is pymupdf lib for text extraction
from bs4 import BeautifulSoup
import requests
from io import StringIO
url = "https://www.blv.admin.ch/blv/de/home/lebensmittel-und-ernaehrung/publikationen-und-forschung/statistik-und-berichte-lebensmittelsicherheit.html"
headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')
all_news = soup.select("div.mod.mod-download a")[0]
pdf = "https://www.blv.admin.ch"+all_news["href"]
#https://www.blv.admin.ch/dam/blv/de/dokumente/lebensmittel-und-ernaehrung/publikationen-forschung/jahresbericht-2017-2019-oew-rr-rasff.pdf.download.pdf/Jahresbericht_2017-2019_DE.pdf这是从pdf中提取文本的代码。当下载文件时,它运行良好:
my_pdf_doc = fitz.open(pdf)
text = ""
for page in my_pdf_doc:
text += page.getText()
print(text)同样的问题是,如果链接没有自动下载pdf文件,例如这个链接:
"https://amsoldingen.ch/images/files/Bekanntgabe-Stimmausschuss-13.12.2020.pdf"如何从文件中提取文本
我也尝试过这个:
pdf_content = requests.get(pdf)
print(type(pdf_content.content))
file = StringIO()
print(file.write(pdf_content.content.decode("utf-32")))但我得到了错误:
Traceback (most recent call last):
File "/Users/aleksandardevedzic/Desktop/pdf extraction scrapping.py", line 25, in <module>
print(file.write(pdf_content.content.decode("utf-32")))
UnicodeDecodeError: 'utf-32-le' codec can't decode bytes in position 0-3: code point not in range(0x110000)发布于 2020-11-25 09:15:13
下面是一个使用PyPDF2的示例。
要安装
pip install PyPDF2
import requests, PyPDF2
from io import BytesIO
url = 'https://www.blv.admin.ch/dam/blv/de/dokumente/lebensmittel-und-ernaehrung/publikationen-forschung/jahresbericht-2017-2019-oew-rr-rasff.pdf.download.pdf/Jahresbericht_2017-2019_DE.pdf'
response = requests.get(url)
my_raw_data = response.content
with BytesIO(my_raw_data) as data:
read_pdf = PyPDF2.PdfFileReader(data)
for page in range(read_pdf.getNumPages()):
print(read_pdf.getPage(page).extractText())输出:
' 1/21 Fad \nŒ 24.08.2020\n Bericht 2017\n Œ 2019: Öffentliche Warnungen, \nRückrufe und Schnellwarnsystem RASFF\n 'https://stackoverflow.com/questions/64986673
复制相似问题