第一步 页面分析
第二步 实现步骤
scrapy startproject book # 爬虫程序名最好不要和爬虫程序重名 scrapy genspider dangdang dangdang.com
# 要运行整个程序的话,只需要运行这个文件 from scrapy import cmdline # cmdline.execute('scrapy crawl db'.split()) cmdline.execute(['scrapy','crawl','dangdang'])
SPIDER_MODULES = ['book.spiders'] NEWSPIDER_MODULE = 'book.spiders' # 去重过滤 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # scheduler队里 SCHEDULER = "scrapy_redis.scheduler.Scheduler" # 数据持久化 SCHEDULER_PERSIST = True ROBOTSTXT_OBEY = False DEFAULT_REQUEST_HEADERS = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en', } # 开启管道 ITEM_PIPELINES = { # 'book.pipelines.BookPipeline': 300, 'scrapy_redis.pipelines.RedisPipeline': 400, }
import scrapy from copy import deepcopy from scrapy_redis.spiders import RedisSpider # 第一步,添加模块 class DangdangSpider(RedisSpider): # 第二步 修改继承的父类 name = 'dangdang' allowed_domains = ['dangdang.com'] # start_urls = ['http://book.dangdang.com/'] #第三步,把start_urls 改写成 reids_key='爬虫文件名字' redis_key = 'dangdang' def parse(self, response): div_list = response.xpath('//div[@class="con flq_body"]/div') for div in div_list: item = {} # 获取大分类 item['b_cate'] = div.xpath('./dl/dt//text()').extract() item['b_cate'] = [i.strip() for i in item['b_cate'] if len(i.strip())>0] dl_list = div.xpath('.//dl[@class="inner_dl"]') for dl in dl_list: # 获取中分类 item['m_cate'] = dl.xpath('./dt//text()').extract() item['m_cate'] = [i.strip() for i in item['m_cate'] if len(i.strip()) > 0] # 获取小分类 a_list = dl.xpath('./dd/a') for a in a_list: item['s_cate'] = a.xpath('./text()').extract_first() item['s_href'] = a.xpath('./@href').extract_first() if item['s_href'] is not None: yield scrapy.Request( url=item['s_href'], callback=self.parse_book_list, meta={'item':deepcopy(item)} ) print(item) def parse_book_list(self,response): item = response.meta.get('item') li_list = response.xpath('//ul[@class="list_aa "]/li') for li in li_list: # 图片的url images/model/guan/url_none.png item['book_img'] = li.xpath('./a[@class="img"]/img/@src').extract_first() if item['book_img'] == 'images/model/guan/url_none.png': item['book_img'] = li.xpath('./a[@class="img"]/img/@data-original').extract_first() # 数据的名字 item['book_name'] = li.xpath('./a[@class="name"]/a/@title').extract_first() # print(item) yield item
import scrapy class BookItem(scrapy.Item): # define the fields for your item here like: name = scrapy.Field() pass