当前位置:   article > 正文

我的第一个Scrapy 程序 - 爬取当当网信息

爬取当当网返回的是什么结构

前面已经安装了Scrapy,下面来实现第一个测试程序。

概述

Scrapy是一个爬虫框架,他的基本流程如下所示(下面截图来自互联网)

我的第一个Scrapy 程序 - 爬取当当网信息

简单的说,我们需要写一个item文件,定义返回的数据结构;写一个spider文件,具体爬取的数据程序,以及一个管道 pipeline 文件,作为后续操作,比如保存数据等等。

下面以当当网为例,看看怎么实现。
这个例子里面我想爬取的内容是前面20页的羽绒服产品,包括产品名字,链接和评论数。

过程

1. 创建一个Scrapy的项目

scrapy startproject dangdang

2. 创建一个爬虫文件**

scrapy genspider -t basic dd dangdang.com

这样他会自动创建一个爬虫文件,结构如下所示:
我的第一个Scrapy 程序 - 爬取当当网信息

3. 编写items.py

items.py

  1. # -*- coding: utf-8 -*-
  2. # Define here the models for your scraped items
  3. #
  4. # See documentation in:
  5. # https://doc.scrapy.org/en/latest/topics/items.html
  6. import scrapy
  7. class DangdangItem(scrapy.Item):
  8. # define the fields for your item here like:
  9. # name = scrapy.Field()
  10. title=scrapy.Field()
  11. url=scrapy.Field()
  12. comment=scrapy.Field()

4. 编写爬虫文件dd.py

前面第二步已经自动生成了一个模板,我们直接修改就行。
dd.py

  1. # -*- coding: utf-8 -*-
  2. import scrapy
  3. from dangdang.items import DangdangItem
  4. from scrapy.http import Request
  5. class DdSpider(scrapy.Spider):
  6. name = 'dd'
  7. allowed_domains = ['dangdang.com']
  8. start_urls = ['http://category.dangdang.com/pg1-cid4010275.html']
  9. def parse(self, response):
  10. item=DangdangItem()
  11. item['title']=response.xpath(u"//a[@dd_name='单品标题']/text()").extract()
  12. item['url']=response.xpath("//a[@dd_name='单品标题']/@href").extract()
  13. item['comment']=response.xpath("//a[@dd_name='单品评论']/text()").extract()
  14. text = response.body
  15. # content_type = chardet.detect(text)
  16. # if content_type['encoding'] != 'UTF-8':
  17. # text = text.decode(content_type['encoding'])
  18. # text = text.encode('utf-8')
  19. # print(text)
  20. yield item
  21. for i in range(2,20):
  22. url='http://category.dangdang.com/pg%d-cid4010275.html'%i
  23. yield Request(url,callback=self.parse)

5. 编写pipelines.py

为了使用pipeline,配置文件需要做个小修改,我顺便关掉了对robot文件的确认
settings.py

  1. ROBOTSTXT_OBEY = False
  2. ITEM_PIPELINES = {
  3. 'dangdang.pipelines.DangdangPipeline': 300,
  4. }

pipeline.py

  1. # -*- coding: utf-8 -*-
  2. # Define your item pipelines here
  3. #
  4. # Don't forget to add your pipeline to the ITEM_PIPELINES setting
  5. # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
  6. import pymysql
  7. class DangdangPipeline(object):
  8. def process_item(self, item, spider):
  9. conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')
  10. for i in range(0,len(item['title'])):
  11. title=item['title'][i]
  12. link=item['url'][i]
  13. comment=item['comment'][i]
  14. print(type(title))
  15. print(title)
  16. # sql="insert into dd(title,link,comment) values ('"+title+"','"+link+"','"+comment+"')"
  17. sql = "insert into dd(title,link,comment) values('" + title + "','" + link + "','" + comment + "')"
  18. try:
  19. conn.query(sql)
  20. except Exception as err:
  21. pass
  22. conn.close()
  23. return item

6. 创建数据库和表

我最后的数据要保存到mysql里面,python里面可以通过pymysql进行操作。我提前在mysql命令行界面里面创建了一个数据库和空表

  1. mysql> create database dangdang;
  2. mysql> create table dd(id int auto_increment primary, title varchar(100), link varchar(100), comment varchar(32));

7. 执行

scrapy crawl dd
如果不想看日志 可以使用
scrapy crawl dd --nolog

8. 检测结果

test.py

  1. #!/usr/bin/env python
  2. #! -*- coding:utf-8 -*-
  3. # Author: Yuan Li
  4. import pymysql
  5. conn=pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='dangdang',use_unicode=True,charset='utf8')
  6. cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
  7. #SQL查询
  8. cursor.execute("select * from dd")
  9. row=cursor.fetchall()
  10. for i in row:
  11. print(i)
  12. conn.close()

结果测试成功

我的第一个Scrapy 程序 - 爬取当当网信息

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/825049
推荐阅读
相关标签
  

闽ICP备14008679号