使用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读写Json涉及到中文的处理方法
Sep 12 Python
详解python中字典的循环遍历的两种方式
Feb 07 Python
python中pylint使用方法(pylint代码检查)
Apr 06 Python
pandas 对每一列数据进行标准化的方法
Jun 09 Python
使用celery执行Django串行异步任务的方法步骤
Jun 06 Python
解决.ui文件生成的.py文件运行不出现界面的方法
Jun 19 Python
python PIL和CV对 图片的读取,显示,裁剪,保存实现方法
Aug 07 Python
Django中使用haystack+whoosh实现搜索功能
Oct 08 Python
pytorch 实现cross entropy损失函数计算方式
Jan 02 Python
python读取当前目录下的CSV文件数据
Mar 11 Python
Python基于Tkinter编写crc校验工具
May 06 Python
Python 键盘事件详解
Nov 11 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
数字转英文
2006/12/06 PHP
用PHP ob_start()控制浏览器cache、生成html实现代码
2010/02/16 PHP
如何在php中正确的使用json
2013/08/06 PHP
php创建sprite
2014/02/11 PHP
ecshop适应在PHP7的修改方法解决报错的实现
2016/11/01 PHP
javascript读取RSS数据
2007/01/20 Javascript
jquery 实现密码框的显示与隐藏示例代码
2013/09/18 Javascript
javascript去掉前后空格的实例
2013/11/07 Javascript
给ListBox添加双击事件示例代码
2013/12/02 Javascript
javascript类型转换使用方法
2014/02/08 Javascript
js提示框替代系统alert,自动关闭alert对话框的实现方法
2016/11/07 Javascript
JS中BOM相关知识点总结(必看篇)
2016/11/22 Javascript
javascript实现简易计算器
2017/02/01 Javascript
基于js中document.cookie全面解析
2017/09/14 Javascript
import与export在node.js中的使用详解
2017/09/28 Javascript
Vue.js 使用v-cloak后仍显示变量的解决方法
2018/11/19 Javascript
微信小程序清空输入框信息与实现屏幕往上滚动的示例代码
2020/06/23 Javascript
[02:08]我的刀塔不可能这么可爱 胡晓桃_1
2014/06/20 DOTA
Python ValueError: invalid literal for int() with base 10 实用解决方法
2015/06/21 Python
python Django模板的使用方法
2016/01/14 Python
python入门基础之用户输入与模块初认识
2016/11/14 Python
Python callable()函数用法实例分析
2018/03/17 Python
django框架之cookie/session的使用示例(小结)
2018/10/15 Python
对python中的try、except、finally 执行顺序详解
2019/02/18 Python
python小技巧——将变量保存在本地及读取
2020/11/13 Python
HTML5拍照和摄像机功能实战详解
2019/01/24 HTML / CSS
美国二手奢侈品寄售网站:TheRealReal
2016/10/29 全球购物
Vichy薇姿加拿大官网:法国药妆,全球专业敏感肌护肤领先品牌
2018/07/11 全球购物
社区工作感言
2014/02/21 职场文书
幼儿园教师演讲稿
2014/05/06 职场文书
运动会口号8字
2014/06/07 职场文书
2014年科室工作总结
2014/11/20 职场文书
大学生学年个人总结
2015/02/15 职场文书
社区公民道德宣传日活动总结
2015/03/23 职场文书
导游词之天津古文化街
2019/11/09 职场文书
Mysql中调试存储过程最简单的方法
2021/06/30 MySQL