python相关工具代码之网络图片下载并显示出下载图片保存到的地址
2023-12-14 18:03:21
# coding=utf-8 from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import time import random import os import urllib.request from bs4 import BeautifulSoup ''' 信号传参类型 pyqtSignal() #无参数信号 pyqtSignal(int) # 一个参数(整数)的信号 pyqtSignal([int],[str] # 一个参数(整数或者字符串)重载版本的信号 pyqtSignal(int,str) #二个参数(整数,字符串)的信号 pyqtSignal([int,int],[int,str]) #二个参数([整数,整数]或者[整数,字符串])重载版本 ''' class Mythread(QThread): # 定义信号,定义参数为str类型 # breakSignal = pyqtSignal(str, list) aaaSignal = pyqtSignal(str,list) def __init__(url, parent=None): super().__init__(parent) def set_url(self,url): self.url = url def get_img_urls(self): try: html = urllib.request.urlopen(self.url).read() soup = BeautifulSoup(html, 'html.parser') img_tags = soup.find_all('img') img_urls = [img['src'] for img in img_tags if img.get('src')] return img_urls except Exception as e: print("Error occurred: ", e) return [] def run(self): img_urls=self.get_img_urls() self.download_imgs(img_urls) def download_imgs(self,img_urls): folder = r'E:\PYthon\python_基础\Python_learn\101_python学习相关\jpg_download' os.makedirs(folder, exist_ok=True) stop = 1 if stop: for i, img_url in enumerate(img_urls): i += 1 # time.sleep(1) try: file_path = os.path.join(folder, f"image_{i}.jpg") urllib.request.urlretrieve(img_url, file_path) txt = f"Downloaded {img_url} {file_path}" print(txt) print(i) self.aaaSignal.emit(txt, [file_path]) except Exception as e: failed_txt = f'Failed to download {img_url} {e}' print(failed_txt) self.aaaSignal.emit(failed_txt, img_urls) # 让程序休眠 time.sleep(1) if __name__ == '__main__': app = QApplication([]) dlg = QDialog() dlg.resize(400, 300) dlg.setWindowTitle("下载图片界面") dlgLayout = QVBoxLayout() dlgLayout.setContentsMargins(40, 40, 40, 40) btn = QPushButton('测试按钮') stop_btn = QPushButton('STOP') load_bth = QPushButton('load') dlgLayout.addWidget(btn) dlgLayout.addWidget(stop_btn) dlgLayout.addStretch(40) dlg.setLayout(dlgLayout) dlg.show() textEdit = QTextEdit() dlgLayout.addWidget(textEdit) thread = Mythread() def stop(): global stop stop = 0 thread.run = 0 btn.setText("停止下载") print('下载停止') def downing_txt(i,img_urls): btn.setText(i) def jpg_load(txt,img_urls): txt_show='\n'.join(img_urls) textEdit.setText(txt_show) stop_btn.clicked.connect(stop) # 创建线程 # # 注册信号处理函数 # thread.breakSignal.connect(chuli) # thread.aaaSignal.connect(downing_txt) thread.aaaSignal.connect(jpg_load) # # 启动线程 url = "https://www.oldboyedu.com" img_urls = thread.set_url(url) # thread.download_imgs(img_urls) thread.start() app.exec_() dlg.exec_() app.exit()
文章来源:https://blog.csdn.net/xtpyc/article/details/134982562
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!