2024年Python最全Python爬取美女写真照的全站异步爬虫,设置了反爬我也要爬给你看

import aiohttp
import aiofiles
import requests
from lxml import etree
import os
import re
from fake_useragent import UserAgent
from functools import wraps
from asyncio.proactor_events import _ProactorBasePipeTransport

def silence_event_loop_closed(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
try:
return func(self, *args, **kwargs)
except RuntimeError as e:
if str(e) != ‘Event loop is closed’:
raise

return wrapper

_ProactorBasePipeTransport.del = silence_event_loop_closed(_ProactorBasePipeTransport.del)
ua = UserAgent()
headers = {‘User-Agent’: ua.random, ‘Referer’: ‘http://www.tulishe.com’}

class tulishe:
def init(self):
self.write_num = 0

async def get_url(self, url):
    async with aiohttp.ClientSession() as client:
        async with client.get(url, headers=headers) as resp:
            if resp.status == 200:
                return await resp.text()

async def html_parse(self, html):
    semaphore = asyncio.Semaphore(5)
    html_parse = etree.HTML(html)
    url_list = html_parse.xpath('//div[@class="img"]//a[@rel="bookmark"]/@href')
    tasks = [asyncio.create_task(self.img_parse(url, semaphore)) for url in url_list]
    await asyncio.wait(tasks)

async def img_parse(self, h_url, sem):
    async with sem:
        semaphore = asyncio.Semaphore(5)
        h_html = await self.get_url(h_url)
        h_html_parse = etree.HTML(h_html)
        title = h_html_parse.xpath('//h1[@class="article-title"]/text()')[0]
        img_demo_url = h_html_parse.xpath(
            '//*[@id="gallery-2"]/div[@class="gallery-item gallery-blur-item"]/img/@src')
        img_url_list = []
        for d_url in img_demo_url:
            img_url = d_url.split('=')[1].split('&')[0]
            img_url_list.append(img_url)
        i_u_l = h_html_parse.xpath(
            '//div[@class="gallery-item gallery-fancy-item"]/a/@href')
        full_list = i_u_l + img_url_list
        index_list = list(range(1, len(full_list) + 1))
        index_dict = dict(zip(full_list, index_list))
        tasks = [asyncio.create_task(self.img_con(i_url, i_num, title, semaphore)) for i_url, i_num in
                 index_dict.items()]
        await asyncio.wait(tasks)

async def img_con(self, url, num, title, semaphore):
    async with semaphore:
        async with aiohttp.ClientSession() as client:
            async with client.get(url, headers=headers) as resp:
                if resp.status == 200:
                    img_con = await resp.read()
                    await self.write_img(img_con, num, title)
                else:
                    print('请求出错,请尝试调低并发数重新下载!!')

async def write_img(self, img_con, num, title):
    if not os.path.exists(title):
        os.makedirs(title)
        async with aiofiles.open(title + '/' + f'{num}.jpg', 'wb') as f:
            print(f'正在下载{title}/{num}.jpg')
            await f.write(img_con)
            self.write_num += 1
    else:
        async with aiofiles.open(title + '/' + f'{num}.jpg', 'wb') as f:
            print(f'正在下载{title}/{num}.jpg')
            await f.write(img_con)
            self.write_num += 1

async def main(self, ):
    q_start_num = input('输入要从第几页开始下载(按Entry默认为1):') or '1'
    start_num = int(q_start_num)
    total_num = int(input('请输入要下载的页数:')) + start_num
    print('*' * 74)
    start_time = time.time()
    for num in range(start_num, total_num + 1):
        url = f'http://www.tulishe.com/all/page/{num}'
        html = await self.get_url(url)
        print('开始解析下载>>>')
        await self.html_parse(html)
    end_time = time.time()
    print(f'本次共下载写真图片{self.write_num}张,共耗时{end_time - start_time}秒。')

a = tulishe()
asyncio.run(a.main())


### 结语:


可以看到,虽然有反爬限制,但1秒10张的速度是完全可以实用的,虽然之前想尝试用代{过}{滤}理池规避,但实际实验后发现,免费的完全不靠谱,可用的又太贵,只是用来日常学习实用,还是采用限制并发比较实际。


### 关于Python技术储备


学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!


包括:Python激活码+安装包、Python web开发,Python爬虫,Python数据分析学习等教程。带你从零基础系统性的学好Python!


#### 一、Python学习大纲


Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/71e2166464ed45959e2863dae1cc4835.jpeg#pic_center)


#### 二、Python必备开发工具


![在这里插入图片描述](https://img-blog.csdnimg.cn/e496e6652efd47f5bbe73ad2ee082d4a.png)


#### 三、入门学习视频
### 一、Python所有方向的学习路线

Python所有方向路线就是把Python常用的技术点做整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。



![](https://img-blog.csdnimg.cn/img_convert/9f49b566129f47b8a67243c1008edf79.png)



### 二、学习软件

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。



![](https://img-blog.csdnimg.cn/img_convert/8c4513c1a906b72cbf93031e6781512b.png)



### 三、入门学习视频



我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。



![](https://img-blog.csdnimg.cn/afc935d834c5452090670f48eda180e0.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA56iL5bqP5aqb56eD56eD,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center)




**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值