Python多线程爬取表情包,代码都放在最后了

本文介绍了如何使用Python进行多线程爬取网络表情包,包括导入模块、替换特殊字符、发送请求、保存数据和主函数的详细步骤,最终展示了爬取和保存结果。

一、写在前面

从老马的两大聊天软件,到其它的各种软件,表情包一直都是中国互联网用户的「心头好」,时至今日,表情包已然成为必不可少的聊天方式。

无论是正事儿还是闲侃,表情包都必不可少,要是聊着聊着发现没得表情包了,多尴尬~

所以它来了,Python批量爬取网络表情包,只要是网上有的,全部都爬下来保存。

二、步骤解析

导入模块

import requests # 数据请求模块
import parsel # 数据解析模块
import re # 正则表达式

替换特殊字符

def change_title(title):
    mode = re.compile(r'[\\\/\:\*\?\"\<\>\|]')
    new_title = re.sub(mode, '_', title)
    return new_title

发送请求

def get_response(html_url):
    headers = {
   
   
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36'
为提高图片爬取爬虫代码的效率,可以从以下几个方面进行优化: ### 多线程或多进程下载 使用Python的`concurrent.futures`模块实现多线程或多进程下载图片,充分利用多核CPU的性能。以下是一个使用多线程的示例代码: ```python import requests import re import os from concurrent.futures import ThreadPoolExecutor image_folder = '表情包' if not os.path.exists(image_folder): os.mkdir(image_folder) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0' } response = requests.get('https://qq.yh31.com/zjbq/', headers=headers) response.encoding = 'GBK' response.encoding = 'utf-8' pattern = '<img src="(.*?)" alt="(.*?)" width="160" height="120">' result = re.findall(pattern, response.text) def download_image(img): try: res = requests.get(img[0]) s = img[0].split('.')[-1] with open(image_folder + '/' + img[1] + '.' + s, mode='wb') as file: file.write(res.content) except Exception as e: print(f"下载图片 {img[1]} 时出错: {e}") with ThreadPoolExecutor(max_workers=10) as executor: executor.map(download_image, result) ``` ### 异步请求 使用`asyncio`和`aiohttp`库实现异步请求,提高网络I/O效率。示例代码如下: ```python import asyncio import aiohttp import re import os image_folder = '表情包' if not os.path.exists(image_folder): os.mkdir(image_folder) headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:98.0) Gecko/20100101 Firefox/98.0' } async def fetch(session, url): async with session.get(url) as response: return await response.read() async def download_image(session, img): try: content = await fetch(session, img[0]) s = img[0].split('.')[-1] with open(image_folder + '/' + img[1] + '.' + s, mode='wb') as file: file.write(content) except Exception as e: print(f"下载图片 {img[1]} 时出错: {e}") async def main(): async with aiohttp.ClientSession(headers=headers) as session: response = await fetch(session, 'https://qq.yh31.com/zjbq/') html = response.decode('GBK') html = html.encode('GBK').decode('utf-8') pattern = '<img src="(.*?)" alt="(.*?)" width="160" height="120">' result = re.findall(pattern, html) tasks = [download_image(session, img) for img in result] await asyncio.gather(*tasks) asyncio.run(main()) ``` ### 减少不必要的请求 在爬取之前,可以先检查图片是否已经存在于本地,避免重复下载。例如在多线程示例代码中,可以添加如下检查逻辑: ```python def download_image(img): s = img[0].split('.')[-1] file_path = image_folder + '/' + img[1] + '.' + s if os.path.exists(file_path): print(f"图片 {img[1]} 已存在,跳过下载") return try: res = requests.get(img[0]) with open(file_path, mode='wb') as file: file.write(res.content) except Exception as e: print(f"下载图片 {img[1]} 时出错: {e}") ```
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值