scrapy spider的几种爬取方式实例代码


Posted in Python onJanuary 25, 2018

本节课介绍了scrapy的爬虫框架,重点说了scrapy组件spider。

spider的几种爬取方式:

  1. 爬取1页内容
  2. 按照给定列表拼出链接爬取多页
  3. 找到‘下一页'标签进行爬取
  4. 进入链接,按照链接进行爬取

下面分别给出了示例

1.爬取1页内容

#by 寒小阳(hanxiaoyang.ml@gmail.com)

import scrapy


class JulyeduSpider(scrapy.Spider):
  name = "julyedu"
  start_urls = [
    'https://www.julyedu.com/category/index',
  ]

  def parse(self, response):
    for julyedu_class in response.xpath('//div[@class="course_info_box"]'):
      print julyedu_class.xpath('a/h4/text()').extract_first()
      print julyedu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first()
      print julyedu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first()
      print response.urljoin(julyedu_class.xpath('a/img[1]/@src').extract_first())
      print "\n"

      yield {
        'title':julyedu_class.xpath('a/h4/text()').extract_first(),
        'desc': julyedu_class.xpath('a/p[@class="course-info-tip"][1]/text()').extract_first(),
        'time': julyedu_class.xpath('a/p[@class="course-info-tip"][2]/text()').extract_first(),
        'img_url': response.urljoin(julyedu_class.xpath('a/img[1]/@src').extract_first())
      }

2.按照给定列表拼出链接爬取多页

#by 寒小阳(hanxiaoyang.ml@gmail.com)

import scrapy


class CnBlogSpider(scrapy.Spider):
  name = "cnblogs"
  allowed_domains = ["cnblogs.com"]
  start_urls = [
    'http://www.cnblogs.com/pick/#p%s' % p for p in xrange(1, 11)
    ]

  def parse(self, response):
    for article in response.xpath('//div[@class="post_item"]'):
      print article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip()
      print response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip()
      print article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip()
      print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip()
      print response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip()
      print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip()
      print article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip()
      print ""

      yield {
        'title': article.xpath('div[@class="post_item_body"]/h3/a/text()').extract_first().strip(),
        'link': response.urljoin(article.xpath('div[@class="post_item_body"]/h3/a/@href').extract_first()).strip(),
        'summary': article.xpath('div[@class="post_item_body"]/p/text()').extract_first().strip(),
        'author': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/a/text()').extract_first().strip(),
        'author_link': response.urljoin(article.xpath('div[@class="post_item_body"]/div/a/@href').extract_first()).strip(),
        'comment': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_comment"]/a/text()').extract_first().strip(),
        'view': article.xpath('div[@class="post_item_body"]/div[@class="post_item_foot"]/span[@class="article_view"]/a/text()').extract_first().strip(),
      }

3.找到‘下一页'标签进行爬取

import scrapy
class QuotesSpider(scrapy.Spider):
  name = "quotes"
  start_urls = [
    'http://quotes.toscrape.com/tag/humor/',
  ]

  def parse(self, response):
    for quote in response.xpath('//div[@class="quote"]'):
      yield {
        'text': quote.xpath('span[@class="text"]/text()').extract_first(),
        'author': quote.xpath('span/small[@class="author"]/text()').extract_first(),
      }

    next_page = response.xpath('//li[@class="next"]/@herf').extract_first()
    if next_page is not None:
      next_page = response.urljoin(next_page)
      yield scrapy.Request(next_page, callback=self.parse)

4.进入链接,按照链接进行爬取

#by 寒小阳(hanxiaoyang.ml@gmail.com)

import scrapy


class QQNewsSpider(scrapy.Spider):
  name = 'qqnews'
  start_urls = ['http://news.qq.com/society_index.shtml']

  def parse(self, response):
    for href in response.xpath('//*[@id="news"]/div/div/div/div/em/a/@href'):
      full_url = response.urljoin(href.extract())
      yield scrapy.Request(full_url, callback=self.parse_question)

  def parse_question(self, response):
    print response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first()
    print response.xpath('//span[@class="a_time"]/text()').extract_first()
    print response.xpath('//span[@class="a_catalog"]/a/text()').extract_first()
    print "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract())
    print ""
    yield {
      'title': response.xpath('//div[@class="qq_article"]/div/h1/text()').extract_first(),
      'content': "\n".join(response.xpath('//div[@id="Cnt-Main-Article-QQ"]/p[@class="text"]/text()').extract()),
      'time': response.xpath('//span[@class="a_time"]/text()').extract_first(),
      'cate': response.xpath('//span[@class="a_catalog"]/a/text()').extract_first(),
    }

总结

以上就是本文关于scrapy spider的几种爬取方式实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

Python 相关文章推荐
解决Python中由于logging模块误用导致的内存泄露
Apr 23 Python
玩转python爬虫之cookie使用方法
Feb 17 Python
java中两个byte数组实现合并的示例
May 09 Python
Python 使用PIL中的resize进行缩放的实例讲解
Aug 03 Python
Python 获取中文字拼音首个字母的方法
Nov 28 Python
python 函数中的内置函数及用法详解
Jul 02 Python
Django密码存储策略分析
Jan 09 Python
python3 使用openpyxl将mysql数据写入xlsx的操作
May 15 Python
Python 实现一个计时器
Jul 28 Python
Python selenium模拟网页点击爬虫交管12123违章数据
May 26 Python
Python Pandas模块实现数据的统计分析的方法
Jun 24 Python
python 中yaml文件用法大全
Jul 04 Python
scrapy爬虫完整实例
Jan 25 #Python
python实现画圆功能
Jan 25 #Python
Python中常用信号signal类型实例
Jan 25 #Python
简单实现python画圆功能
Jan 25 #Python
Python中sort和sorted函数代码解析
Jan 25 #Python
django在接受post请求时显示403forbidden实例解析
Jan 25 #Python
Python微信公众号开发平台
Jan 25 #Python
You might like
用phpmyadmin更改mysql5.0登录密码
2008/03/25 PHP
php中用文本文件做数据库的实现方法
2008/03/27 PHP
php Hex RGB颜色值互换的使用
2013/05/10 PHP
php快速查找数据库中恶意代码的方法
2015/04/01 PHP
PHP实现的购物车类实例
2015/06/17 PHP
php实现微信发红包
2015/12/05 PHP
prototype 中文参数乱码解决方案
2009/11/09 Javascript
JavaScript模板入门介绍
2012/09/26 Javascript
简介JavaScript中setUTCSeconds()方法的使用
2015/06/12 Javascript
基于javascript实现页面加载loading效果
2020/09/15 Javascript
Linux下为Node.js程序配置MySQL或Oracle数据库的方法
2016/03/19 Javascript
JS常见疑难点分析之match,charAt,charCodeAt,map,search用法分析
2016/12/25 Javascript
JS变量及其作用域
2017/03/29 Javascript
vue-cli下的vuex的简单Demo图解(实现加1减1操作)
2018/02/26 Javascript
详解vue-router 初始化时做了什么
2018/06/11 Javascript
详解Vue 匿名、具名和作用域插槽的使用方法
2019/04/22 Javascript
微信小程序利用Canvas绘制图片和竖排文字详解
2019/06/25 Javascript
[51:05]DOTA2上海特级锦标赛主赛事日 - 5 败者组决赛Liquid VS EG第一局
2016/03/06 DOTA
Python中使用urllib2模块编写爬虫的简单上手示例
2016/01/20 Python
通过Python 接口使用OpenCV的方法
2018/04/02 Python
pyqt5 删除layout中的所有widget方法
2019/06/25 Python
K最近邻算法(KNN)---sklearn+python实现方式
2020/02/24 Python
Python threading.local代码实例及原理解析
2020/03/16 Python
python+selenium实现12306模拟登录的步骤
2021/01/21 Python
MSC邮轮官方网站:加勒比海、地中海和世界各地的假期
2018/08/27 全球购物
Moda Operandi官网:美国奢侈品电商,海淘秀场T台同款
2020/05/26 全球购物
法国低价在线宠物商店:bitiba.fr
2020/07/03 全球购物
数控专业大学生的自我鉴定
2013/11/13 职场文书
环境工程专业自荐信范文
2014/03/18 职场文书
十八大宣传标语
2014/10/09 职场文书
离婚协议书范本2014
2014/10/27 职场文书
公司财务人员岗位职责
2015/04/14 职场文书
义卖募捐活动总结
2015/05/09 职场文书
活动简报范文
2015/07/22 职场文书
党校团干班培训心得体会
2016/01/06 职场文书
四则混合运算教学反思
2016/02/23 职场文书