2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Scrapy框架——CrawlSpider爬取某热线网站

时间:09-13来源:作者:点击数:40

CrawlSpider

Scrapy框架中分两类爬虫,Spider类和CrawlSpider类。

它是Spider的派生类,Spider类的设计原则是只爬取start_url列表中的网页,

而CrawlSpider类定义了一些规则(rule)来提供跟进link的方便的机制,从爬取的网页中获取link并继续爬取的工作更适合。

创建项目指令:

  • scrapy startproject sumPro

CrawlSpider创建:

  • scrapy genspider -t crawl sun "http://wz.sun0769.com"

LinkExtractor 链接提取器

根据指定规则进行指定链接的提取

  • from scrapy.linkextractors import LinkExtractor
  • LinkExtractor(allow=r'start=\d+')
  • 通过实例化LinkExtractor提取链接
  • 主要参数
  • allow:满足括号中“正则表达式”的值会被提取,如果为空,则全部匹配。
  • deny:与这个正则表达式(或正则表达式列表)不匹配的URL一定不提取。

rules 规则解析器

将链接提取器提取到的链接进行指定规则(callback)解析操作

  • Rule(LinkExtractor(allow=r'start=\d+'), callback='parse_tencent', follow=True),
  • 在rules中包含一个或多个Rule对象,每个Rule对爬取网站的动作定义了特定操作。
  • 如果多个rule匹配了相同的链接,则根据规则在本集合中被定义的顺序,第一个会被使用
  • 主要参数
  • 复制代码
  • link_extractor:是一个Link Extractor对象,用于定义需要提取的链接
  • callback: 从link_extractor中每获取到链接时,参数所指定的值作为回调函数,该回调函数接受一个response作为其第一个参数。
  • 注意:当编写爬虫规则时,避免使用parse作为回调函数。由于CrawlSpider使用parse方法来实现其逻辑,如果覆盖了 parse方法,crawl spider将会运行失败。
  • follow:是一个布尔(boolean)值,指定了根据该规则从response提取的链接是否需要跟进。 如果callback为None,follow 默认设置为True ,否则默认为False

使用CrawlSpider爬取信息

spider文件

  • import scrapy
  • from scrapy.linkextractors import LinkExtractor
  • from scrapy.spiders import CrawlSpider, Rule
  • from sunPro.items import SunproItem,DetailproItem
  • # 爬取sun网站中的编号,标题,内容
  • class SunSpider(CrawlSpider):
  • name = 'sun'
  • # allowed_domains = ['www.xxx.com']
  • start_urls = ['http://wz.sun0769.com/political/index/politicsNewest?id=1&page=1']
  • link = LinkExtractor(allow=r'id=1&page=\d+') # 标题链接提取器 根据指定规则(allow)指定提取
  • # http://wz.sun0769.com/political/politics/index?id = 449762
  • link_detail = LinkExtractor(allow=r'/politics/index\?id=\d+') # 详情页链接提取器 根据指定规则(allow)指定提取
  • rules = (
  • # 规则解析器 :将链接提取器提取到的链接进行指定规则(callback)解析操作
  • Rule(link, callback='parse_item', follow=True),
  • # follow=True 链接提取器 循环提取
  • Rule(link_detail, callback='parse_detail')
  • )
  • def parse_item(self, response):
  • news_list = response.xpath('//ul[@class="title-state-ul"]/li')
  • for new_item in news_list:
  • new_num = new_item.xpath('./span[@class="state1"]/text()').extract_first()
  • new_title = new_item.xpath('./span[@class="state3"]/a/text()').extract_first()
  • item = SunproItem()
  • item['new_num'] = new_num
  • item['new_title'] = new_title
  • # print('new_title:{}'.format(new_title))
  • yield item
  • def parse_detail(self, response):
  • """
  • 新闻内容
  • :param response:
  • :return:
  • """
  • # print('parse_detail:', response)
  • detail_item = DetailproItem()
  • news_content = response.xpath('//div[@class="details-box"]/pre/text()').extract_first()
  • detail_item['new_content'] = news_content
  • # print('new_content:{}'.format(news_content))
  • yield detail_item

item文件

  • import scrapy
  • class SunproItem(scrapy.Item):
  • # define the fields for your item here like:
  • # name = scrapy.Field()
  • new_num = scrapy.Field()
  • new_title = scrapy.Field()
  • pass
  • class DetailproItem(scrapy.Item):
  • new_content = scrapy.Field()

pipeline文件

  • # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
  • from sunPro.items import SunproItem,DetailproItem
  • class SunproPipeline(object):
  • def process_item(self, item, spider):
  • if isinstance(item,DetailproItem):
  • print('DetailproItem:{}'.format(item['new_content']))
  • else:
  • print('SunproItem:{}:{}'.format(item['new_num'],item['new_title']))
  • return item
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门