from lxml import etree import requests import os print("米娜这个东西要开全局代理才能看呢!") handers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69'} whileTrue: page = input("大家好越江又来送好东西了,这次是图片哦,每一页有三十四个系列的图片,最多八十页哦!请输入您要的页数: ") ifint(page) > 80orint(page) <= 0: print("不要就不要,乱输什么数字啊!") else: break ifnot os.path.exists("好东西2"): print('正在爬取网址') os.makedirs('好东西2') pic_dict = dict() for pagex inrange(1, int(page) + 1): try: url = f'http://www.52rosi.com/?action=ajax_post&pag={pagex}' res = requests.get(url,headers=handers) res.encoding='utf-8' page_text = res.text tree = etree.HTML(page_text) print(f'{pagex / int(page) * 100}%...正在爬取网址') for index inrange(1,33): pic_nam = tree.xpath(f'//div[@class="post-home"][{index}]//span/a/@title') pic_name = pic_nam[0].replace("上的评论",' ') pic_url = tree.xpath(f'//div[@class="post-home"][{index}]//span/a/@href') pic_dict[pic_name] = pic_url[0] except: print(f'第{page}页出错了') print(res.status_code)
withopen('./好东西2/各个网址.txt',mode='w',encoding='utf-8') as fp: fp.write(str(pic_dict))
tip = 0 for item_name,item_url in pic_dict.items(): tip += 1 print(f"{tip / len(pic_dict.keys()) * 100}%正在帮你下载图片") os.makedirs(f'./好东西2/{item_name}') res = requests.get(item_url,headers=handers) tree = etree.HTML(res.text) url_list = tree.xpath('//div[@id="wrap"]//dt[@class="gallery-icon"]/a/@href') for index,urlx inenumerate(url_list):
res = requests.get(urlx, headers=handers) withopen(f"./好东西2/{item_name.strip()}/{index}.jpg",mode='wb') as f: f.write(res.content)
else: print("把当前目录下的“好东西”文件夹删了,我才好给你资源啊!")
3.高性能异步爬虫
3.1异步爬虫的方式
·多线程,多进程(不建议)
·线程池,进程池(建议)
下面线程池的使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import time # 导入线程池所对应的类 from multiprocessing import Pool #模拟下载 defget_page(str): print("正在下载", str) time.sleep(2) print("下载成功", str) if __name__ == '__main__': listx = ['aa','ss','vv','bb'] #实例化一个线程池对象 pool = Pool(4)#创建了四个线程 #将列表中每一个元素传递个get pool.map(get_page,listx)
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
classSuilianItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() content_url = scrapy.Field() content = scrapy.Field()#新定义的属性 pass
在爬虫文件中把内容传入到item类中去,并且给属性赋值,然后将数据提交给管道。
随后我们就爬取到了碎脸小说
下面放一下各个文件的源码
suilian.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
import scrapy from SUILIAN.items import SuilianItem
classSuilianSpider(scrapy.Spider): name = 'suilian' #allowed_domains = ['www.xxx.com'] start_urls = ['http://www.daomushu.com/suilian/']
# Scrapy settings for SUILIAN project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html
# Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69'
# Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default) #COOKIES_ENABLED = False
# Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False
# Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False
# Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface from itemadapter import ItemAdapter
# Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
classSuilianItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() content_url = scrapy.Field() content = scrapy.Field() pass