pdf读取函数,可以读取本地pdf和url的在线pdf转换为文字

python 复制代码
import requests
from lxml import etree
import os
import urllib
from PIL import Image
from pymysql.converters import escape_string
import sys
import time
from selenium import webdriver
import warnings
import pdfplumber
from urllib import request
import io
import socks
import urllib.parse
import pymysql
import socks
import configparser
import hashlib
import threading
import urllib.parse
import re


def read_pdf(path,proxies={},timeout=(3.2,10),download_image=False):
    f=''
    if path=='' or type(path)!=str:
        print("路径为空或格式不对!")
    if path[0:4]=="http":
        try:
            #data=request.urlopen(path,timeout=10).read()
            print(proxies)
            data=requests.get(url=path,timeout=timeout,proxies=proxies)
            f = io.BytesIO(data.content)
        except Exception as e:
            print(e,"打开链接失败")
            return ''
    else:
        try:
            path=urllib.parse.unquote(path)
            path=path.replace('file:///','').replace('/','\\')
            f=open(path,'rb')
        except Exception as e:
            print(e,"打开本地文件失败")

    text=''
    old_path=os.getcwd()
    if download_image:
        im_path=path.replace('https://','').replace("http://",'')
        os.makedirs(im_path, exist_ok=True)
        os.chdir(im_path)
    
    with pdfplumber.open(f) as pdf:
    # 遍历每个页面
        for page in pdf.pages:
            # 获取当前页面的全部文本信息,包括表格中的文字,没有内容则打印None
            text+=page.extract_text()
            if download_image:
                images=page.images
                i=0
                for img in images:
                    f_img=open('{}.png'.format(i),'wb+')
                    f_img.write(img['stream'].get_data())
                    f_img.close()
                    i+=1
    os.chdir(old_path)
    f.close()
    return text

可用库自己筛选一下,我把全部的加进来了,proxies是http代理,path是路径,download_image是是否存成本地图片文件。

相关推荐
m0_7349497915 小时前
MySQL如何配置定时清理过期备份文件_find命令与保留周期策略
jvm·数据库·python
m0_5145205716 小时前
MySQL索引优化后性能没提升_通过EXPLAIN查看索引命中率
jvm·数据库·python
H Journey16 小时前
Python 国内pip install 安装缓慢
python·pip·install 加速
Polar__Star17 小时前
如何在 AWS Lambda 中正确使用临时凭证生成 S3 预签名 URL
jvm·数据库·python
m0_7436239218 小时前
React 自定义 Hook 的命名规范与调用规则详解
jvm·数据库·python
FreakStudio18 小时前
无硬件学LVGL—定时器篇:基于Web模拟器+MicroPython速通GUI开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
gCode Teacher 格码致知19 小时前
Python提高:pytest的简单案例-由Deepseek产生
python·pytest
不要秃头的小孩19 小时前
力扣刷题——509. 斐波那契数
python·算法·leetcode·动态规划
科雷软件测试19 小时前
使用python+Midscene.js AI驱动打造企业级WEB自动化解决方案
前端·javascript·python
weipt19 小时前
发票打印还在花钱?这款免费小工具,A4纸一半大小、自动排版,真香!
pdf·发票打印