使用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 相关文章推荐
easy_install python包安装管理工具介绍
Feb 10 Python
python爬取51job中hr的邮箱
May 14 Python
python django事务transaction源码分析详解
Mar 17 Python
python如何定义带参数的装饰器
Mar 20 Python
利用arcgis的python读取要素的X,Y方法
Dec 22 Python
python实现弹跳小球
May 13 Python
opencv导入头文件时报错#include的解决方法
Jul 31 Python
pytorch查看torch.Tensor和model是否在CUDA上的实例
Jan 03 Python
解决python DataFrame 打印结果不换行问题
Apr 09 Python
python定义类的简单用法
Jul 24 Python
Python pip使用超时问题解决方案
Aug 03 Python
用python 绘制茎叶图和复合饼图
Feb 26 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
PHP小技巧搜集,每个PHPer都来露一手
2007/01/02 PHP
Zend Framework教程之Zend_Helpers动作助手ViewRenderer用法详解
2016/07/20 PHP
thinkphp中多表查询中防止数据重复的sql语句(必看)
2016/09/22 PHP
javascript与webservice的通信实现代码
2010/12/25 Javascript
jQuery find和children方法使用
2011/01/31 Javascript
jsTree 基于JQuery的排序节点 Bug
2011/07/26 Javascript
Jquery index()方法 获取相应元素索引值
2012/10/12 Javascript
JS获取图片实际宽高及根据图片大小进行自适应
2013/08/11 Javascript
在Node.js应用中使用Redis的方法简介
2015/06/24 Javascript
全面解析Bootstrap图片轮播效果
2015/12/03 Javascript
jQuery实现响应鼠标事件的图片透明效果【附demo源码下载】
2016/06/16 Javascript
【经验总结】编写JavaScript代码时应遵循的14条规律
2016/06/20 Javascript
Vue通过for循环随机生成不同的颜色或随机数的实例
2019/11/09 Javascript
vue vant Area组件使用详解
2019/12/09 Javascript
[59:44]2018DOTA2亚洲邀请赛 3.31 小组赛 B组 paiN vs iG
2018/03/31 DOTA
[01:27:44]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Aster BO3 第一场 1月24日
2021/03/11 DOTA
Python MySQL数据库连接池组件pymysqlpool详解
2017/07/07 Python
Python实现的求解最小公倍数算法示例
2018/05/03 Python
Python环境管理virtualenv&virtualenvwrapper的配置详解
2020/07/01 Python
PyCharm2019 安装和配置教程详解附激活码
2020/07/31 Python
CSS3 伪类选择器 nth-child()说明
2010/07/10 HTML / CSS
Ann Taylor官方网站:美国最大的女性产品制造商之一
2016/09/14 全球购物
台湾网友喜爱的综合型网路购物商城:Yahoo! 奇摩购物中心
2018/03/10 全球购物
美国眼镜网站:LensCrafters
2020/01/19 全球购物
荣耀商城:HIHONOR
2020/11/03 全球购物
公司年会演讲稿范文
2014/01/11 职场文书
企业宣传口号
2014/06/12 职场文书
幼儿教师师德师风演讲稿
2014/08/22 职场文书
县政府班子个人对照检查材料
2014/10/05 职场文书
2014年信访工作总结
2014/11/17 职场文书
2014年副班长工作总结
2014/12/10 职场文书
总经理检讨书范文
2015/02/16 职场文书
2015年度保密工作总结
2015/04/24 职场文书
2015年基层党建工作总结
2015/05/14 职场文书
读《儒林外史》有感:少一些功利,多一些真诚
2020/01/19 职场文书
mysql 生成连续日期及变量赋值
2022/03/20 MySQL