scrapy框架
CrawlSpider
CrawlSpider:基于Spider的子类,继承父类的功能,且派生出自己的功能。
全站数据爬取的方式
- 基于Spider:手动请求发送
- 基于CrawlSpider:
基本使用
创建一个工程
scrapy startproject quanzhanPro
切换到工程目录
cd quanzhanPro
创建一个基于CrawlSpider类的爬虫文件
scrapy genspider -t crawl quanzhan wz.sun0769.com/political/index/politicsNewest
生成的爬虫文件
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class QuanzhanSpider(CrawlSpider):
name = 'quanzhan'
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 = {
}
#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
链接提取器 LinkExtractor
根据指定规则(allow=‘正则’)提取符合规则的链接(会自动去重)
link = LinkExtractor(allow=r'id=1&page=/d+')
规则解析器 Rule
将链接提取器提取到的链接进行指定规则(callback)的解析操作
follow=True 全站数据爬取(进入到提取的页面继续提取匹配的链接)
Rule(LinkExtractor(allow=