用Python从PDF url文件中提取文本

用Python从PDF url文件中提取文本,python,pdf,beautifulsoup,Python,Pdf,Beautifulsoup,我想从一个网站上的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/le

我想从一个网站上的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)
回溯(最近一次呼叫最后一次):
文件“/Users/aleksandardevedzic/Desktop/pdf extraction scrapsing.py”,第25行,在
打印(file.write(pdf_content.content.decode(“utf-32”))
UnicodeDecodeError:“utf-32-le”编解码器无法解码位置0-3中的字节:代码点不在范围内(0x110000)

下面是一个使用PyPDF2的示例

安装

pip安装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      '

你可以使用BytesIO下载到内存中的某个空间:这对我不起作用,它给我带来了错误/你能告诉我如何在我的代码中应用它吗,也许我做错了什么只是增加了循环问题是我得到的结果到处都是,没有组织问题超出了范围。回答了第一个问题(如何在不下载的情况下阅读pdf文件)。现在,我建议您通过访问本图书馆的文档了解如何阅读pdf: