Python全系列 教程
3567个小节阅读:5931.3k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在Scrapy中Spider是所有爬虫的基类,而CrawSpiders就是Spider的派生类。
适用于先爬取start_url列表中的网页,再从爬取的网页中获取link并继续爬取的工作。运行图如下
xxxxxxxxxx
scrapy genspider -t crawl 爬虫名 (allowed_url)
Rule类与CrawlSpider类都位于scrapy.contrib.spiders
模块中
xxxxxxxxxx
class scrapy.contrib.spiders.Rule(
link_extractor,
callback=None,
cb_kwargs=None,
follow=None,
process_links=None,
process_request=None)
参数含义:
link_extractor为LinkExtractor,用于定义需要提取的链接
callback参数:当link_extractor获取到链接时参数所指定的值作为回调函数
注意 回调函数尽量不要用parse方法,crawlspider已使用了parse方法
follow:指定了根据该规则从response提取的链接是否需要跟进。当callback为None,默认值为True
process_links:主要用来过滤由link_extractor获取到的链接
process_request:主要用来过滤在rule中提取到的request
顾名思义,链接提取器
response对象中获取链接,并且该链接会被接下来爬取 每个LinkExtractor有唯一的公共方法是 extract_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象
xxxxxxxxxx
class scrapy.linkextractors.LinkExtractor(
allow = (),
deny = (),
allow_domains = (),
deny_domains = (),
deny_extensions = None,
restrict_xpaths = (),
tags = ('a','area'),
attrs = ('href'),
canonicalize = True,
unique = True,
process_value = None
)
主要参数:
首先运行
xxxxxxxxxx
scrapy shell 'https://www.zhhbqg.com/1_1852/835564.html'
继续import相关模块:
xxxxxxxxxx
from scrapy.linkextractors import LinkExtractor
提取当前网页中获得的链接
xxxxxxxxxx
link = LinkExtractor(restrict_xpaths=(r'//a'))
调用LinkExtractor实例的extract_links()方法查询匹配结果
xxxxxxxxxx
link.extract_links(response)
xxxxxxxxxx
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from xiaoshuo.items import XiaoshuoItem
class XiaoshuoSpiderSpider(CrawlSpider):
name = 'xiaoshuo_spider'
allowed_domains = ['fhxiaoshuo.com']
start_urls = ['http://www.fhxiaoshuo.com/read/33/33539/17829387.shtml']
rules = [
Rule(LinkExtractor(restrict_xpaths=(r'//div[@class="bottem"]/a[4]')), callback='parse_item'),]
def parse_item(self, response):
info = response.xpath("//div[@id='TXT']/text()").extract()
it = XiaoshuoItem()
it['info'] = info
yield it
注意
- callback后面函数名用引号引起
- 函数名不要用parse
- 参数的括号嵌套,不要出问题
实时效果反馈
1. 关于Scrapy, CrawlSpider说法错误的是?
A 用于设置爬取URL与提取数据
B 解析的函数不能使用parse
C 使用rules参数来定义提取url的规则
D 使用LinkExtractor设置提取url的规则
答案
1=>B