CrawlSpider
CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。
创建crawlspider
scrapy genspider -t crawl spiderName www.xxx.com
LinkExtractors 链接提取器
class scrapy.linkextractors.LinkExtractor
LinkExtractors的目的很简单:提取链接。
每个LinkExtractors有唯一的公共方法是extract_links(),他接收一个response对象,并返回一个scrapy.link.Link对象
Linkextractors要实例化一次,并且extract_links方法会根据不同的response调用多次提取链接
参数
-
allow:满足括号中“正则表达式”的值会被提取,如果为空,则会全部匹配
-
deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取
-
allow_domains:会被提取的链接domains
-
deny_domains:一定不会被提取链接的domains
-
restrick_xpaths:使用xpath表达式,和allow共同作用过滤链接
注意:restrict_xpaths 应该指向元素,也就是直接链接或包含链接的容器,而不是它的属性(例如:普通的xpath是:
//div/a/@href,restrict_xpaths应该是://div/a)
rules
在rules中包含一个或多个Rule对象
每个Rule对爬取网站的动作定义了特定的操作。
如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用
参数
- link_extractors:是一个LinkExtractor对象,用于定义需要提取的链接
- callback:从link_extractor中没获取链接时,参数所制定的值作为回调函数,该回调函数接受一个response作为起第一个参数
注意:当编写爬虫规则是,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了parse方法,CrawlSpider将会运行失败 - follow:是一个布尔值(boolean),制定了根据该规则从response提取的链接是否需要跟进
- process_links:指定该Spider中那个的函数将会被调用,从link_extractor中获取到链接列表是将会调用该函数。该方法主要用来过滤
- process_request:指定该Spider中那个的函数将会被调用,该规则提取到每个request是都会调用该函数。(用来过滤request)
简单理解
- 爬虫从start_urls发起第一个请求,收到回复response1
- 根据rule中定义的规则从response1中匹配出对应的url
- 再用这些url发起请求,收到回复response2
- 再查找response2中有无匹配的url,再发送请求,直到没有匹配的url
示例
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy_movie.items import ScrapyMovieItem
class CrawlmovieSpider(CrawlSpider):
name = 'crawlmovie'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://www.ygdy8.net/html/gndy/oumei/index.html']
rules = (
Rule(LinkExtractor(allow=r'/html/gndy/[A-Za-z]+/\d+/\d+\.html'), callback='parse_item', follow=True),
Rule(LinkExtractor(restrict_xpaths=('//div[@class="co_content8"]/ul//b/a[2]')), callback='parse_item',
follow=True),
)
def parse_item(self, response):
if response.status == 200:
url = response.xpath('//div[@id="Zoom"]//a/@href').extract_first()
name = response.xpath('//div[@class="co_area2"]/div/h1/font/text()').extract_first()
if url:
src_url = response.url.split('/')
src_url[-1] = url
url = "/".join(src_url)
if len(url) > 1000:
url = 'url too long'
else:
url = 'None'
movie = ScrapyMovieItem(url=url, name=name)
yield movie

浙公网安备 33010602011771号