目录
- name:爬虫的名字
- allowed_domins:域名限制
- start_urls:开始URL
- custom_settings: ⼀个字典 专属于本spider的配置 这个配置覆盖项⽬全局配置,配置需要在初始化前更新,定义类变量,可以更新请求头。
start_requests(self):可以重新定义开始发送的请求。(翻页使用)

- url:请求的⽹址
- callback:回调函数
- method:请求⽅法 默认get
- headers: 请求头
- body:请求主体
- cookies: 携带记录的信息
- meta:携带额外参数
- priority:请求优先级
- dont_filter: reqest不去重 设置True
- errback:错误处理⽅法
- flags: 请求的标志
- cb_kwargs:回调⽅法的额外参数
- import scrapy
- from my_scrapy.items import MyScrapyItem
- from fake_useragent import UserAgent
-
-
- class SpiderSpider(scrapy.Spider):
- # 爬虫名称
- name = 'spider'
- # 域名限制,允许爬取的范围
- # allowed_domains = ['https://quotes.toscrape.com/']
-
- base_url = 'https://quotes.toscrape.com/page/{}/'
-
- # 初始请求的页面
- start_urls = ['https://quotes.toscrape.com/']
-
- headers = [{'user-agent': UserAgent().random}]
- cookies = {'name': 'zqh'}
-
- def start_request(self):
- for page in range(1, 6):
- url = self.base_url.format(page)
- yield scrapy.Request(url=url, callback=self.parse, headers=self.headers, cookies=self.cookies)
-
- def parse(self, response):
- # text = response.text
-
- quotes = response.xpath('//div[@class="quote"]')
- for quote in quotes:
- # 旧方法 get()为新方法
- # text = quote.xpath('./span[@class = "text"]/text()').extract_first()
-
- # 实例化对象
- item = MyScrapyItem()
-
- # 利用xpth进行爬取
- text = quote.xpath('./span[@class = "text"]/text()').get()
- author = quote.xpath('.//small[@class="author"]/text()').get()
- Tags = quote.xpath('.//a[@class="tag"]/text()').getall()
- item['text'] = text
- item['author'] = author
- item['Tag'] = Tags
-
- # 迭代出去
- yield item
-
- # 简洁的拼接
- # yield from response.follow_all(response.css('.pager .next a::attr("href")'), callback=self.parse)
- url
- status:状态码
- headers
- request:
- body:Response Body 通常指的就是访问⽹⻚后得到的⽹
- certicate:通过代表⼀个SSL证书对象
- ip_address:代表服务器地址
- urljoin: 是对url的⼀个处理⽅法,可以传⼊当前⻚⾯的相对
- follow/follow_all:是⼀个根据url来⽣成后续Request的⽅
- text
- encoding
- selector
- xpath()
- css()
- json(): 2.2以后版本更新的⽅法 直接将text属性转为json对
- 象