使用Scrapy爬取动态数据


Posted in Python onOctober 21, 2018

对于动态数据的爬取,可以选择seleniumPhantomJS两种方式,本文选择的是PhantomJS。

网址:

https://s.taobao.com/search?q=%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306

1.首先第一步,对中间件的设置。

进入pipelines.py文件中:

from selenium import webdriver
from scrapy.http.response.html import HtmlResponse
from scrapy.http.response import Response
class SeleniumSpiderMiddleware(object):
  def __init__(self):
    self.driver = webdriver.PhantomJS()
  def process_request(self ,request ,spider):
    # 当引擎从调度器中取出request进行请求发送下载器之前
    # 会先执行当前的爬虫中间件 ,在中间件里面使用selenium
    # 请求这个request ,拿到动态网站的数据 然后将请求
    # 返回给spider爬虫对象
    if spider.name == 'taobao':
      # 使用爬虫文件的url地址
      spider.driver.get(request.url)
      for x in range(1 ,12 ,2):
        i = float(x) / 11
        # scrollTop 从上往下的滑动距离
        js = 'document.body.scrollTop=document.body.scrollHeight * %f' % i
        spider.driver.execute_script(js)
      response = HtmlResponse(url=request.url,
                  body=spider.driver.page_source,
                  encoding='utf-8',
                  request=request)
      # 这个地方只能返回response对象,当返回了response对象,那么可以直接跳过下载中间件,将response的值传递给引擎,引擎又传递给 spider进行解析
      return response

在设置中,要将middlewares设置打开。

进入settings.py文件中,将

DOWNLOADER_MIDDLEWARES = {
  'taobaoSpider.middlewares.SeleniumSpiderMiddleware': 543,
}

打开。

2.第二步,爬取数据

回到spider爬虫文件中。

引入:

from selenium import webdriver

自定义属性:

def __init__(self):
  self.driver = webdriver.PhantomJS()

查找数据和分析数据:

def parse(self, response):
  div_info = response.xpath('//div[@class="info-cont"]')
  print(div_info)
  for div in div_info:
    title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
    # title = self.driver.find_element_by_class_name("title-row").text
    print('名称:', title)
    price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')

3.第三步,传送数据到item中:

item.py文件中:

name = scrapy.Field()
price = scrapy.Field()

回到spider.py爬虫文件中:

引入:

from ..items import TaobaospiderItem

传送数据:

#创建实例化对象。

item = TaobaospiderItem()
item['name'] = title
item['price'] = price
yield item

在设置中,打开:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

4.第四步,写入数据库:

进入管道文件中。

引入

import sqlite3
写入数据库的代码如下:
class TaobaospiderPipeline(object):
  def __init__(self):
    self.connect = sqlite3.connect('taobaoDB')
    self.cursor = self.connect.cursor()
    self.cursor.execute('create table if not exists taobaoTable (name text,price text)')
  def process_item(self, item, spider):
    self.cursor.execute('insert into taobaoTable (name,price)VALUES ("{}","{}")'.format(item['name'],item['price']))
    self.connect.commit()
    return item
  def close_spider(self):
    self.cursor.close()
    self.connect.close()

在设置中打开:

ITEM_PIPELINES = {
  'taobaoSpider.pipelines.TaobaospiderPipeline': 300,
}

因为在上一步,我们已经将管道传送设置打开,所以这一步可以不用重复操作。

然后运行程序,打开数据库查看数据。

使用Scrapy爬取动态数据

至此,程序结束。

下附spider爬虫文件所有代码:

# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from ..items import TaobaospiderItem
class TaobaoSpider(scrapy.Spider):
  name = 'taobao'
  allowed_domains = ['taobao.com']
  start_urls = ['https://s.taobao.com/search?q=%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.2017.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170306']
  def __init__(self):
    self.driver = webdriver.PhantomJS()
  def parse(self, response):
    div_info = response.xpath('//div[@class="info-cont"]')
    print(div_info)
    for div in div_info:
      title = div.xpath('.//div[@class="title-row "]/a/text()').extract_first('')
      print('名称:', title)
      price = div.xpath('.//div[@class="sale-row row"]/div/span[2]/strong/text()').extract_first('')
      item = TaobaospiderItem()
      item['name'] = title
      item['price'] = price
      yield item
  def close(self,reason):
    print('结束了',reason)
    self.driver.quit()

关于scrapy的中文文档:http://scrapy-chs.readthedocs.io/zh_CN/latest/faq.html

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对三水点靠木的支持。如果你想了解更多相关内容请查看下面相关链接

Python 相关文章推荐
Python类的多重继承问题深入分析
Nov 09 Python
python使用Image处理图片常用技巧分析
Jun 01 Python
python基于multiprocessing的多进程创建方法
Jun 04 Python
Ubuntu下创建虚拟独立的Python环境全过程
Feb 10 Python
python时间日期函数与利用pandas进行时间序列处理详解
Mar 13 Python
Django自定义过滤器定义与用法示例
Mar 22 Python
解决Python 命令行执行脚本时,提示导入的包找不到的问题
Jan 19 Python
在cmd中查看python的安装路径方法
Jul 03 Python
Python如何获取文件指定行的内容
May 27 Python
套娃式文件夹如何通过Python批量处理
Aug 23 Python
Python 实现集合Set的示例
Dec 21 Python
Python try except finally资源回收的实现
Jan 25 Python
python使用正则表达式来获取文件名的前缀方法
Oct 21 #Python
python遍历文件夹找出文件夹后缀为py的文件方法
Oct 21 #Python
python os.listdir按文件存取时间顺序列出目录的实例
Oct 21 #Python
python查找指定文件夹下所有文件并按修改时间倒序排列的方法
Oct 21 #Python
Python3中关于cookie的创建与保存
Oct 21 #Python
Python3中在Anaconda环境下安装basemap包
Oct 21 #Python
解决安装python库时windows error5 报错的问题
Oct 21 #Python
You might like
火影忍者:三大瞳力之一的白眼,为什么没有写轮眼那么出色?
2020/03/02 日漫
php set_include_path函数设置 include_path 配置选项
2016/10/30 PHP
bindParam和bindValue的区别以及在Yii2中的使用详解
2018/03/12 PHP
DIY jquery plugin - tabs标签切换实现代码
2010/12/11 Javascript
jQuery点击tr实现checkbox选中的方法
2013/03/19 Javascript
javascript:json数据的页面绑定示例代码
2014/01/26 Javascript
浅谈NodeJS中require路径问题
2015/05/07 NodeJs
js获取图片宽高的方法
2015/11/25 Javascript
jquery 无限极下拉菜单的简单实例(精简浓缩版)
2016/05/31 Javascript
js图片上传前预览功能(兼容所有浏览器)
2016/08/24 Javascript
JS对大量数据进行多重过滤的方法
2016/11/04 Javascript
AngularJS遍历获取数组元素的方法示例
2017/11/11 Javascript
three.js实现3D模型展示的示例代码
2017/12/31 Javascript
Vue 中axios配置实例详解
2018/07/27 Javascript
Vue watch响应数据实现方法解析
2020/07/10 Javascript
JS实现拖动模糊框特效
2020/08/25 Javascript
[00:32]2018DOTA2亚洲邀请赛VG出场
2018/04/03 DOTA
使用python解析xml成对应的html示例分享
2014/04/02 Python
Python做文本按行去重的实现方法
2016/10/19 Python
python实现的正则表达式功能入门教程【经典】
2017/06/05 Python
django中的HTML控件及参数传递方法
2018/03/20 Python
Python3 中把txt数据文件读入到矩阵中的方法
2018/04/27 Python
python读取图片任意范围区域
2019/01/23 Python
Python使用QQ邮箱发送邮件报错smtplib.SMTPAuthenticationError
2019/12/20 Python
Python list运算操作代码实例解析
2020/01/20 Python
京东全球售:直邮香港,澳门,台湾,美国,澳大利亚等地区
2017/09/24 全球购物
泰坦健身器材:Titan Fitness
2018/02/13 全球购物
美国林业供应商:Forestry Suppliers
2019/05/01 全球购物
会计专业大学生职业生涯规划范文
2014/01/11 职场文书
家长写给孩子的评语
2014/04/18 职场文书
求职信模板
2014/05/23 职场文书
2014高三学生考试作弊检讨书
2014/12/14 职场文书
家长会感言
2015/08/01 职场文书
高三语文教学反思
2016/02/16 职场文书
Java 获取Word中所有的插入和删除修订的方法
2022/04/06 Java/Android
flex布局中使用flex-wrap实现换行的项目实践
2022/06/21 HTML / CSS