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是是否存成本地图片文件。

相关推荐
奕成则成12 分钟前
Python 创建虚拟环境
开发语言·python
lambo mercy1 小时前
python入门
前端·数据库·python
0和1的舞者1 小时前
Python函数与列表元组全解析
python·学习·学习方法·知识
2401_841495641 小时前
【机器学习】限制性玻尔兹曼机(RBM)
人工智能·python·深度学习·神经网络·机器学习·无监督学习·限制性玻尔兹曼机
我送炭你添花1 小时前
Pelco KBD300A 模拟器:06+3.从教学级到企业级工程化转型(二次迭代)
python·测试工具·运维开发
不要em0啦2 小时前
从0开始学python:简单的练习题4
开发语言·python
小李云雾2 小时前
Python 多任务编程入门:进程的创建、同步与进程池使用
开发语言·数据库·python·oracle
AI Echoes2 小时前
LangChain中的工具与工具包
人工智能·python·langchain·prompt·agent
我爱娃哈哈2 小时前
SpringBoot集成:5分钟实现HTML转PDF功能
spring boot·pdf·html
浔川python社2 小时前
浔川社团 2026 更新程序安排
python