python公众号图片采集工具

15 阅读2分钟

使用Python编写的图形用户界面(GUI)应用程序,结合了PyQt6库和requests库以及BeautifulSoup库来实现一个简单的公众号图片采集工具。

实现代码

import os
import sys
import requests
import re
from bs4 import BeautifulSoup
from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QPushButton, QMessageBox, QLabel
from datetime import datetime

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 设置窗口标题和大小
        self.setWindowTitle("公众号图片采集")
        # 前两位是窗口坐标,后两位是窗口大小
        self.setGeometry(300, 300, 240, 120)

        # 创建一个水平布局
        layout = QVBoxLayout()

        # 创建一个文本
        self.label = QLabel("图片一定不存在C盘", self)

        # 创建一个输入框
        self.lineEdit = QLineEdit(self)
        # 设置输入框的Qt样式表
        self.lineEdit.setStyleSheet("""
            QLineEdit {
                border: 1px solid #4CAF50; /* 设置边框样式 */
                border-radius: 5px; /* 设置边框圆角 */
                padding: 2px; /* 设置内边距 */
                background-color: #f0f0f0; /* 设置背景颜色 */
                color: black; /* 设置文本颜色 */
                font-size: 16px; /* 设置字体大小 */
            }

            QLineEdit:focus {
                border-color: #008000; /* 当输入框获得焦点时改变边框颜色 */
            }
        """)
        self.lineEdit.setPlaceholderText("请输入链接")

        # 创建一个按钮
        self.button = QPushButton('提交', self)
        # 设置按钮的样式
        self.button.setStyleSheet("""
            QPushButton {
                background-color: #4CAF50; /* 绿色背景 */
                color: white; /* 白色文字 */
                border-style: outset; /* 外凸边框 */
                border-width: 2px; /* 边框宽度 */
                border-radius: 10px; /* 边框圆角 */
                border-color: beige; /* 边框颜色 */
                font: bold 14px; /* 字体加粗,字号14 */
                padding: 6px; /* 内边距 */
            }

            QPushButton:pressed {
                background-color: #388E3C; /* 按下时的背景颜色 */
            }
        """)

        self.button.clicked.connect(self.fetch_and_copy_div)

        # 将输入框和按钮添加到布局中
        layout.addWidget(self.label)
        layout.addWidget(self.lineEdit)
        layout.addWidget(self.button)

        # 设置窗口的布局
        self.setLayout(layout)

    def fetch_and_copy_div(self):
        # 获取输入框中的内容self.lineEdit.text()
        url = self.lineEdit.text()
        html = self.getHTMLText(url)
        img_url = self.getimgURL(html)
        # print(img_url)
        self.download(img_url)
        QMessageBox.information(self, "提示", "下载完成")

    # 获取网页信息
    def getHTMLText(self, url):
        try:
            response = requests.get(url, timeout=30)
            response.raise_for_status()
            response.encoding = response.apparent_encoding
            return response.text
        except requests.RequestException as e:
            QMessageBox.information(self, "提示", "请求错误")
            return ""

    # 解析网页,获取所有图片url
    def getimgURL(self, html):
        soup = BeautifulSoup(html, "html.parser")
        image_urls = []
        for i in soup.find_all("img"):
            try:
                ad = re.findall(r'.*src="(.*?)?" .*', str(i))
                if ad:
                    image_urls.append(ad)
            except KeyError:  # 如果src属性不存在,‌尝试使用data-src属性(‌某些情况下图片链接可能放在这里)‌
                try:
                    image_url = i['data-src']  # 尝试获取data-src属性作为备用方案
                    if 'http' in image_url:  # 检查是否为完整的URL并添加到列表中
                        image_urls.append(image_url)
                except:
                    continue
        return image_urls

    # 新建文件夹pic,下载并保存爬取的图片信息
    def download(self, urls):
        # 获取当前时间
        now = datetime.now()

        # 格式化当前时间
        formatted_now = now.strftime("%Y%m%d%H%M")

        # 设置文件目录
        root = "C:\公众号爬取\" + formatted_now + "\"

        if not os.path.exists(root):
            os.makedirs(root)

        # 遍历URLs并下载
        for index, url in enumerate(urls):
            try:
                response = requests.get(url[0], timeout=30)
                response.raise_for_status()

                # 尝试根据 Content-Type 设置文件扩展名
                content_type = response.headers.get('Content-Type')

                if content_type:
                    ext = content_type.split('/')[-1].lower()
                    if ext in ['jpeg', 'jpg', 'png', 'gif']:
                        ext = ext
                    else:
                        ext = 'bin'  # 如果不是常见图片格式,则保存为二进制文件
                else:
                    ext = 'bin'

                path = os.path.join(root, f"{index}.{ext}")

                with open(path, 'wb') as f:
                    f.write(response.content)

            except requests.RequestException as e:
                QMessageBox.information(self, "错误", f"无法下载图片: {e}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec())

链接:pan.quark.cn/s/15f97562a…

提取码:bDXi