首页 > 编程问答 >扫描 PDF 中的 QR-Code,提取后面的 URL 并检查 URL 的状态代码

扫描 PDF 中的 QR-Code,提取后面的 URL 并检查 URL 的状态代码

时间:2024-07-25 05:00:41浏览次数:8  
标签:python qr-code

我们重新启动了一个网站和数百个不同语言的 PDF 以及硬打印的 QR 代码。

重新启动后,我们遇到了问题,某些 QR 代码未链接到正确的 UR。 为了减少工作量,我的想法是加载所有 PDF,扫描 QR 码,从 pdf 中提取 URL 并发出请求,该请求是 URL 的状态代码 200(并有一个包含所有文档和链接的表格)。|| |但是我的代码找不到 QR 码。

有任何帮助修复吗?

不同的代码和应用程​​序

import os
import requests
import fitz  # PyMuPDF
import cv2
from pyzbar.pyzbar import decode
import numpy as np
import csv
import pdfplumber

# Funktion zum Herunterladen der PDFs
def download_pdf(url, save_path):
    if os.path.exists(save_path):
        print(f"{save_path} already exists, skipping download.")
        return True
    response = requests.get(url)
    if response.status_code == 200:
        with open(save_path, 'wb') as f:
            f.write(response.content)
        print(f"Downloaded {url}")
        return True
    else:
        print(f"Failed to download {url}, status code: {response.status_code}")
        return False

# Funktion zum Konvertieren von PDF-Seiten in Bilder mit PyMuPDF
def pdf_to_images(pdf_path):
    doc = fitz.open(pdf_path)
    images = []
    for page in doc:
        pix = page.get_pixmap()
        if pix.alpha:
            img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 4)
        else:
            img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, 3)
        images.append(img)
    return images

# Funktion zum Extrahieren von QR-Codes aus einem Bild
def extract_qr_codes(image):
    qr_codes = decode(image)
    return [qr.data.decode('utf-8') for qr in qr_codes]

# Funktion zum Überprüfen der URL und Rückgabe des Statuscodes
def check_url(url):
    try:
        response = requests.head(url, allow_redirects=True)
        return response.status_code
    except requests.RequestException as e:
        print(f"Error checking URL {url}: {e}")
        return 'Error'

# Alternative Methode zur Bildextraktion mit pdfplumber
def extract_images_and_decode_qr(pdf_path):
    with pdfplumber.open(pdf_path) as pdf:
        for page in pdf.pages:
            im_list = page.images
            for im in im_list:
                bbox = (im['x0'], im['top'], im['x1'], im['bottom'])
                cropped_image = page.crop(bbox).to_image(resolution=300)
                image = np.array(cropped_image.original)
                image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
                qr_codes = decode(image)
                for qr in qr_codes:
                    print("Gefundener QR-Code:", qr.data.decode())

# Hauptfunktion zum Verarbeiten der PDFs
def process_pdfs(url_list):
    results = []
    for url in url_list:
        pdf_filename = os.path.basename(url)
        pdf_path = os.path.join('downloads', pdf_filename)
        
        if not os.path.exists('downloads'):
            os.makedirs('downloads')
        
        if download_pdf(url, pdf_path):
            print(f"Processing {pdf_path}...")
            images = pdf_to_images(pdf_path)
            for img in images:
                qr_urls = extract_qr_codes(img)
                for qr_url in qr_urls:
                    status_code = check_url(qr_url)
                    results.append((pdf_filename, qr_url, status_code))

            # Versuchen Sie es mit pdfplumber, wenn keine QR-URLs gefunden wurden
            if not any(result[1] for result in results if result[0] == pdf_filename):
                extract_images_and_decode_qr(pdf_path)

    if results:
        with open('results.csv', 'w', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['PDF Name', 'QR Code', 'Target URL', 'Status Code'])
            for result in results:
                writer.writerow(result)
    else:
        print("No results to write to CSV.")

# Testaufruf für URLs
if __name__ == "__main__":
    url_list = [
        "https:.....pdf"
    ]
    
    process_pdfs(url_list)

期望:QR 码后面的 URL 的状态代码,以及 QR 码检测作为基本。

Expecting: Status Code of the URL behind QR-Code, and QR-Code detection as basic.


你的代码看起来很有条理,而且思路正确!问题可能出在 QR 码的检测方法上,特别是如果 QR 码很小或者分辨率低的时候。

让我们来优化你的代码以便更可靠地检测和处理 QR 码:

import os
import requests
import fitz  # PyMuPDF
import cv2
from pyzbar.pyzbar import decode
import numpy as np
import csv
import pdfplumber

# 函数用于下载 PDF 文件
def download_pdf(url, save_path):
    # ... (代码不变) 

# 函数用于使用 PyMuPDF 将 PDF 页面转换为图像
def pdf_to_images(pdf_path):
    # ... (代码不变) 

# 函数用于从图像中提取 QR 码
def extract_qr_codes(image):
    qr_codes = decode(image)
    if qr_codes:
        return [qr.data.decode('utf-8') for qr in qr_codes]
    else:
        # 如果使用默认设置找不到 QR 码,请尝试使用更高的分辨率
        resized_image = cv2.resize(image, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
        qr_codes = decode(resized_image)
        if qr_codes:
            return [qr.data.decode('utf-8') for qr in qr_codes]
        else:
            return []

# 函数用于检查 URL 并返回状态代码
def check_url(url):
    # ... (代码不变) 

# 使用 pdfplumber 提取图像并解码 QR 码的备用方法
def extract_images_and_decode_qr(pdf_path):
    # ... (代码不变)

# 主要函数用于处理 PDF 文件
def process_pdfs(url_list):
    results = []
    for url in url_list:
        # ... (代码不变) 

            # ... (代码不变) 

            # 尝试使用 pdfplumber,如果使用 PyMuPDF 找不到 QR URL,则尝试使用 pdfplumber
            if not any(result[1] for result in results if result[0] == pdf_filename):
                print(f"Trying with pdfplumber for {pdf_filename}...")
                extract_images_and_decode_qr(pdf_path)

    # ... (代码不变) 

# 用于 URL 的测试调用
if __name__ == "__main__":
    # ... (代码不变)

改进之处:

  1. 提高 QR 码检测的可靠性:
  2. 如果在初始尝试中未找到 QR 码,我们现在会使用 cv2.resize 函数放大图像。这可以帮助检测较小或分辨率较低的 QR 码。
  3. 增强的错误处理:
  4. 如果 extract_qr_codes 函数在调整大小后仍未找到任何 QR 码,则返回一个空列表,以避免错误并继续处理。
  5. 更清晰的日志记录:
  6. 添加了一条消息,指示何时使用 pdfplumber 作为备用方法。

其他提示:

  • QR 码质量: 确保 PDF 文件中的 QR 码清晰且分辨率足够高。低质量的 QR 码可能难以检测。
  • QR 码大小: 如果 QR 码相对于页面大小而言过小,则可能需要更积极地调整图像大小或考虑在检测之前裁剪页面区域。
  • 对比度: 确保 QR 码与其背景之间有足够的对比度。

通过这些改进,你的代码应该能够更可靠地从 PDF 文件中提取 QR 码并检查其 URL。如果仍然遇到问题,请提供示例 PDF 文件或图像,以便我进行进一步调查!

标签:python,qr-code
From: 78790546

相关文章

  • Python XML 解析:字符串中的“<”被阻塞
    我有一个使用ET.XMLParser来解析CppCheckXML报告文件的Python模块。当尝试解析字符串中包含“<”的XML元素中的属性之一时,它会令人窒息,它会将其解释为格式错误的XML,例如:<errormsg="Includefile<iostream>notfound.">(注意字符和“iostream”之间的空格必须放......
  • 任意几行代码要成为Python中的函数需要什么?
    我正在上一门计算机科学课,我的任务是创建一个程序来实现一个带有参数的函数。我的老师告诉我,下面的代码不是一个函数,这让我很困惑,对于将某些代码行归类为“函数”所需的条件,我感到很困惑。defgame(numbers,max_turns,pfl,tgl):turns=0flag=Falseprint("You......
  • 如何使用 Python 创建新的 Azure 订阅?
    我正在尝试使用PythonSDK以编程方式创建新的Azure订阅。我发现的对AzurePythonSDK的唯一引用是这个这是我最终得到的结果:importazure.mgmt.billingimportazure.mgmt.subscriptioncreds=AzureCliCredential()client_name='test'defcreat......
  • 用于打印脚本输出的 Python 实用程序
    我可以发誓有一个实用程序可以打印一个python脚本,其输出交织在一起。例如,给定一个脚本:a=2b=3print(a+b)print(a*b)该实用程序将输出a=2b=3print(a+b)#>5print(a*b)#>6有人知道该实用程序的名称吗?我最难找到它。谢谢你!描述的实用程序没有标......
  • a method to make some handy tools with python
    Inmyworkingofcomputer,therearealotofsimplejobsthatarefrequentlyrepeated.Itriedtofindawaytomakethesejobbeenprocessedeasily.Method1:Themethodiswritingascripttodothejob,andexecutingthescriptbyutoolsextensionuto......
  • Python网络爬虫详解:实战豆瓣电影信息采集
    文章目录前言一、爬虫是什么?二、常用库及其作用1.Requests2.BeautifulSoup3.lxml4.Scrapy5.Selenium6.PyQuery7.Pandas8.JSON9.Time三、实现步骤步骤一:环境准备步骤二:数据采集步骤三:数据处理步骤四:数据存储总结前言随着互联网的迅猛发展和数据分析需求的不......
  • python学习之内置函数
    Python拥有许多内置函数,这些函数是Python的一部分,不需要额外导入即可直接使用。这些函数提供了对Python解释器功能的直接访问,涵盖了从数学计算到类型检查、从内存管理到异常处理等各个方面。下面是一些常用的Python内置函数及其简要说明:一、Printprint函数大家都不会......
  • Python中以函数为作用域
    点击查看代码#第一题foriteminrange(10):#不报错,没有函数,所有操作在全局作用域里面执行,item最后赋值为:9,此时item在缩进与全局都可以使用passprint(item)#第二题item=10deffunc():foriteminrange(10):#优先在本地查找,找不到在到全局查找p......
  • 掌握IPython宏:%%macro命令的高效使用指南
    掌握IPython宏:%%macro命令的高效使用指南在编程中,宏是一种允许你定义可重用代码片段的强大工具。IPython,这个增强版的Python交互式环境,提供了一个名为%%macro的魔术命令,允许用户创建宏,从而提高代码的可重用性和效率。本文将详细介绍如何在IPython中使用%%macro命令创建宏,并......
  • 7月24号python:库存管理
    7月24号python:库存管理题目:​ 仓库管理员以数组stock形式记录商品库存表。stock[i]表示商品id,可能存在重复。原库存表按商品id升序排列。现因突发情况需要进行商品紧急调拨,管理员将这批商品id提前依次整理至库存表最后。请你找到并返回库存表中编号的最小的元素以便及......