1. 什么是crawlspider
- 需求:
- 如对网页中某人物详情、招聘详情、商品详情的链接提取
- 并且不断的通过下一页自动递归的提取全部链接
- 功能:
- 能够根据一定的匹配规则进行匹配从response中提取链接
- 自动构建request请求发送给引擎
2. 如何实现
2.1 通过crawlspider模板创建爬虫文件
在创建的爬虫项目中创建爬虫文件
scrapy genspider -t crawl jnu_crawl jnu.edu.cn
此时修改jnu_crawl.py文件
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class JnuCrawlSpider(CrawlSpider):
name = 'jnu_crawl'
allowed_domains = ['jnu.edu.cn']
# 1. 修改起始url
start_urls = ['http://xxxy2016.jnu.edu.cn/Category_16/Index.aspx']
# 2. 修改提取规则
rules = (
Rule(LinkExtractor(allow=r'/Item/\d+.aspx'), callback='parse_item', follow=False),
)
def parse_item(self, response):
# 对提取到的详情页面处理,可以提取相关内容
print(response.url)
item = {}
item['edu'] = response.xpath('//*[@id="Education"]/div[2]/p/span/text()').extract()
print(item)
# item['link'] = response.xpath('')
#item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
#item['name'] = response.xpath('//div[@id="name"]').get()
#item['description'] = response.xpath('//div[@id="description"]').get()
return item