start_urls = ['http://tencent.com/']
rules = (
Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
)
def parse_item(self, response):
i = {}
#i['domain_id'] = response.xpath('//input[@id="sid"]/@value').extract()
#i['name'] = response.xpath('//div[@id="name"]').extract()
#i['description'] = response.xpath('//div[@id="description"]').extract()
return i
Link Extractors 的目的很简单: 提取链接。
每个LinkExtractor有唯一的公共方法是 extract\_links(),它接收一个 Response 对象,并返回一个 scrapy.link.Link 对象。
LinkExtractors要实例化一次,并且 extract\_links 方法会根据不同的 response 调用多次提取链接。
**主要参数:**
allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。
allow\_domains:会被提取的链接的domains。
deny\_domains:一定不会被提取链接的domains。
restrict\_xpaths:使用xpath表达式,和allow共同作用过滤链接。
###### rules
在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用。
参数介绍:
LinkExtractor:是一个Link Extractor对象,用于定义需要提取的链接。
callback: 从link\_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数
follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为
None,follow 默认设置为
True ,否则默认为
False。
process\_links:指定该spider中哪个的函数将会被调用,从link\_extractor中获取到链接列表时将会调用该函数。该方法主要用来过滤。
process\_request:指定该spider中哪个的函数将会被调用, 该规则提取到每个request时都会调用该函数。 (用来过滤request)
以下是案例代码:
##### item文件
import scrapy
class TencentItem(scrapy.Item):
# 职位
name = scrapy.Field()
# 详情链接
positionlink = scrapy.Field()
#职位类别
positiontype = scrapy.Field()
# 人数
peoplenum = scrapy.Field()
# 工作地点
worklocation = scrapy.Field()
# 发布时间
publish = scrapy.Field()
##### pipeline文件
import json
class TencentPipeline(object):
def __init__(self):
self.filename = open("tencent.json", "w")
def process_item(self, item, spider):
text = json.dumps(dict(item), ensure_ascii = False) + ",\n"
self.filename.write(text.encode("utf-8"))
return item
def close_spider(self, spider):
self.filename.close()
##### setting文件
BOT_NAME = ‘tencent’
SPIDER_MODULES = ['tencent.spiders']
NEWSPIDER_MODULE = 'tencent.spiders'
LOG_FILE = 'tenlog.log'
LOG_LEVEL = 'DEBUG'
LOG_ENCODING = 'utf-8'
ROBOTSTXT_OBEY = True
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
# 'Accept-Language': 'en',
}
ITEM_PIPELINES = {
'tencent.pipelines.TencentPipeline': 300,
}
##### spider文件
-- coding: utf-8 --
import scrapy
# 导入链接匹配规则类,用来提取符合规则的链接
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from tencent.items import TencentItem
现在能在网上找到很多很多的学习资源,有免费的也有收费的,当我拿到1套比较全的学习资源之前,我并没着急去看第1节,我而是去审视这套资源是否值得学习,有时候也会去问一些学长的意见,如果可以之后,我会对这套学习资源做1个学习计划,我的学习计划主要包括规划图和学习进度表。
分享给大家这份我薅到的免费视频资料,质量还不错,大家可以跟着学习
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!