GUI--协程--图片爬虫, 轻量级可视化窗口爬取百度图片
import asyncio
from aiohttp import ClientSession
from tkinter import *
from tkinter.filedialog import *
from os.path import exists
from json import loads
# 图片下载器
async def download_image(url, session, path):
async with session.get(url) as response:
if response.status == 200:
data = await response.read()
with open(path, 'wb') as f:
f.write(data)
# 图片爬取
async def download_images(urls, path):
async with ClientSession() as session:
tasks = [download_image(url, session, f'{path}/{i}.jpg') for i, url in enumerate(urls)]
await asyncio.gather(*tasks)
# GUI事件处理
def crawl_images(url, path):
asyncio.run(download_images(loads(url.get())['data'], path.get()))
# GUI界面初始化
def create_gui(root):
Label(root, text='图片爬取URL').pack()
url = Entry(root)
url.pack()
url.insert(0, 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/image?query=Python&word=Python&pn=0&ie=utf-8')
Label(root, text='保存路径').pack()
path = Entry(root)
path.pack()
path.insert(0, './images')
Button(root, text='爬取', command=lambda: crawl_images(url, path)).pack()
root.mainloop()
if __name__ == '__main__':
root = Tk()
root.title('图片爬取')
create_gui(root)
这段代码使用了Tkinter库创建了一个简单的GUI界面,允许用户输入图片爬取的URL和图片保存路径。当用户点击"爬取"按钮时,会启动一个异步的图片爬取过程,图片会被异步下载并保存到指定的文件夹中。这个例子展示了如何将异步IO操作和GUI事件处理结合起来,是一个简单的网络爬虫和GUI结合的例子。
评论已关闭