CrawlSpider类是什么?
-
是Spider的一个子类
-
区别:
-
Spider是获取到URL进行 手动发送请求 : yield scrapy.Request(url=new_url,callback=self.parse)
-
是通过提取器类:LinkExtractor,提前到页面所有符合条件的URL,然后用Rule类对符合条件的URL自动发送请求
-
创建CrawlSpider爬虫的命令:scrapy genspider -t crawl xxx(爬虫名称) www.xxxx.com(爬取的URL)
基于CrawlSpider创建的爬虫类,代码示例:
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class XuexiSpider(CrawlSpider):
name = 'xuexi'
allowed_domains = ['www.xxx.com']
start_urls = ['http://www.xxx.com/']
rules = (
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
)
def parse_item(self, response):
item = {}
return item
下面也一个案例,就以爬取阳光信息网为例,代码示例:
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from sunPro.items import SunproItem,DetailItem
class SunSpider(CrawlSpider):
name = 'sun'
start_urls = ['http://wz.sun0769.com/index.php/question/questionType?type=4&page=']
link = LinkExtractor(allow=r'type=4&page=\d+')
link_detail = LinkExtractor(allow=r'question/\d+/\d+\.shtml')
rules = (
Rule(link, callback='parse_item', follow=True),
Rule(link_detail,callback='parse_detail')
)
def parse_item(self, response):
tr_list = response.xpath('//*[@id="morelist"]/div/table[2]//tr/td/table//tr')
for tr in tr_list:
new_num = tr.xpath('./td[1]/text()').extract_first()
new_title = tr.xpath('./td[2]/a[2]/@title').extract_first()
item = SunproItem()
item['title'] = new_title
item['new_num'] = new_num
yield item
def parse_detail(self,response):
new_id = response.xpath('/html/body/div[9]/table[1]//tr/td[2]/span[2]/text()').extract_first()
new_content = response.xpath('/html/body/div[9]/table[2]//tr[1]//text()').extract()
new_content = ''.join(new_content)
item = DetailItem()
item['content'] = new_content
item['new_id'] = new_id
yield item
import scrapy
class SunproItem(scrapy.Item):
title = scrapy.Field()
new_num = scrapy.Field()
class DetailItem(scrapy.Item):
new_id = scrapy.Field()
content = scrapy.Field()
class SunproPipeline(object):
def process_item(self, item, spider):
if item.__class__.__name__ == 'DetailItem':
print(item['new_id'],item['content'])
pass
else:
print(item['new_num'],item['title'])
return item
出处:https://www.cnblogs.com/zhiqianggege/p/16203841.html