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实现udp数据报传输的方法
Sep 26 Python
使用numba对Python运算加速的方法
Oct 15 Python
Pycharm+Scrapy安装并且初始化项目的方法
Jan 15 Python
使用Python画股票的K线图的方法步骤
Jun 28 Python
Python3环境安装Scrapy爬虫框架过程及常见错误
Jul 12 Python
django rest framework 实现用户登录认证详解
Jul 29 Python
解决在pycharm运行代码,调用CMD窗口的命令运行显示乱码问题
Aug 23 Python
Python不支持 i ++ 语法的原因解析
Jul 22 Python
Python利用Faiss库实现ANN近邻搜索的方法详解
Aug 03 Python
Python JSON常用编解码方法代码实例
Sep 05 Python
教你使用一行Python代码玩遍童年的小游戏
Aug 23 Python
python Tkinter模块使用方法详解
Apr 07 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
mysql 字段类型说明
2007/04/27 PHP
深入PHP获取随机数字和字母的方法详解
2013/06/06 PHP
PHP利用hash冲突漏洞进行DDoS攻击的方法分析
2015/03/26 PHP
javascript 解析后的xml对象的读取方法细解
2009/07/25 Javascript
Javascript中typeof 用法小结
2015/05/12 Javascript
JavaScript中setMonth()方法的使用详解
2015/06/11 Javascript
JavaScript中字符串拼接的基本方法
2015/07/07 Javascript
javascript实现无缝上下滚动特效
2015/12/16 Javascript
JavaScript通过HTML的class来获取HTML元素的方法总结
2016/05/24 Javascript
Listloading.js移动端上拉下拉刷新组件
2016/08/04 Javascript
JavaScript实战之菜单特效
2016/08/16 Javascript
AngularJS全局scope与Isolate scope通信用法示例
2016/11/22 Javascript
jQuery插件ajaxFileUpload使用详解
2017/01/10 Javascript
javascript实现多张图片左右无缝滚动效果
2017/03/22 Javascript
Vue-cli创建项目从单页面到多页面的方法
2017/09/20 Javascript
Vue项目从webpack3.x升级webpack4不完全指南
2019/04/28 Javascript
React+Redux实现简单的待办事项列表ToDoList
2019/09/29 Javascript
vue h5移动端禁止缩放代码
2019/10/28 Javascript
微信小程序获取复选框全选反选选中的值(实例代码)
2019/12/17 Javascript
Vue 打包体积优化方案小结
2020/05/20 Javascript
python获取目录下所有文件的方法
2015/06/01 Python
Python调用C语言的方法【基于ctypes模块】
2018/01/22 Python
Django ORM 聚合查询和分组查询实现详解
2019/08/09 Python
Numpy中的数组搜索中np.where方法详细介绍
2021/01/08 Python
Spy++的使用方法及下载教程
2021/01/29 Python
HTML5 script元素async、defer异步加载使用介绍
2013/08/23 HTML / CSS
红色康乃馨酒店:Red Carnation Hotels
2017/06/22 全球购物
IGK Hair官网:喷雾、洗发水、护发素等
2020/11/03 全球购物
深圳-东方伟业笔试部分
2015/02/11 面试题
市场营销专业个人自荐信格式
2013/09/21 职场文书
担保书范本
2015/01/20 职场文书
单位接收函范文
2015/01/30 职场文书
超市收银员岗位职责
2015/04/07 职场文书
通知范文怎么写
2015/04/16 职场文书
2015年乡镇人大工作总结
2015/04/22 职场文书
MYSQL 的10大经典优化案例场景实战
2021/09/14 MySQL