Scrapy实例2、爬取靓号网

超、凢脫俗 2022-12-27 01:19 252阅读 0赞

前言:通过实例学习了解Scrapy爬虫框架的使用,并把爬取到的数据保存到数据库中和保存成一个Json格式的文件。

项目分析:

项目名:phone 爬虫名:getphone 爬取的网址:http://www.jihaoba.com/escrow/ 集号吧

分析爬取的字段:

  1. //div[@class="numbershow"]/ul

手机号码:

  1. ./li[@class="number hmzt"]/a/@href

需要使用正则匹配获取电话号码

  1. re("\\d{11}") # 11位电话号码

在这里插入图片描述

价格:

  1. ./li[@class="price"]/span/text()

存入数据库需要对人民币符号进行格式处理

  1. replace("¥", "")

在这里插入图片描述

归属地:

  1. ./li[@class="brand"]/brand/text()

在这里插入图片描述

项目流程:

  1. 创建项目

    1. scrapy startproject phone
  2. 创建爬虫器

    1. cd phone
    2. scrapy genspider getphone jihaoba.com
  3. 设计爬虫器

    1. from ..items import PhoneItem
    2. class GetphoneSpider(scrapy.Spider):
    3. name = 'getphone'
    4. allowed_domains = ['jihaoba.com']
    5. start_urls = ['http://www.jihaoba.com/escrow/']
    6. def parse(self, response):
    7. # print(response)
    8. lists = response.xpath('//div[@class="numbershow"]/ul')
    9. for list in lists:
    10. phoneitem = PhoneItem()
    11. # 电话号码
    12. phoneitem['number'] = list.xpath('li[@class="number hmzt"]/a/@href').re("\\d{11}")[0]
    13. # 价格
    14. price = list.xpath('li[@class="price"]/span/text()').extract()[0]
    15. phoneitem['price'] = price.replace("¥", "")
    16. # 归属地
    17. phoneitem['brand'] = list.xpath('li[@class="brand"]/text()').extract()[0]
    18. # print(number, price, brand)
    19. yield phoneitem
    20. # 继续下一页
    21. # next = "http://www.jihaoba.com" + response.xpath('//a[@class="m-pages-next"]/@href').extract_first()
    22. # yield scrapy.Request(next)
  4. 设置项目 items

    1. class PhoneItem(scrapy.Item):
    2. # define the fields for your item here like:
    3. # name = scrapy.Field()
    4. number = scrapy.Field()
    5. price = scrapy.Field()
    6. brand = scrapy.Field()
  5. 设置管道 pipelines

    1. import MySQLdb
    2. from .settings import mysql_host, mysql_user, mysql_passwd, mysql_db, mysql_port
    3. # 保存到数据库
    4. class putMySQLPipeline:
    5. def __init__(self):
    6. host = mysql_host
    7. user = mysql_user
    8. passwd = mysql_passwd
    9. db = mysql_db
    10. port = mysql_port
    11. # 连接数据库
    12. self.connection = MySQLdb.connect(host, user, passwd, db, port, charset='utf8')
    13. # 获取游标
    14. self.cursor = self.connection.cursor()
    15. def process_item(self, item, spider):
    16. sql = "insert into phonetable(number,price,brand) values(%s,%s,%s)"
    17. param = list() # 创建列表存放数据
    18. param.append(item['number'])
    19. param.append(item['price'])
    20. param.append(item['brand'])
    21. self.cursor.execute(sql, tuple(param)) # 执行操作,tuple()表示将列表转换为元组
    22. self.connection.commit() # 提交事务
    23. return item
    24. def __del__(self):
    25. self.cursor.close()
    26. self.connection.close()
    27. class JsonWithEncodingPipeline(object):
    28. def __init__(self):
    29. self.file = codecs.open("phone.json", "a", encoding="utf-8")
    30. def process_item(self, item, spider):
    31. lines = json.dumps(dict(item), ensure_ascii=False) + "\n" # dict() 创建一个字典
    32. self.file.write(lines)
    33. return item
    34. def __del__(self):
    35. self.file.close()
  6. 设置 settings

    1. # Configure item pipelines
    2. # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
    3. # 管道优先级(数字越小优先级越高)
    4. ITEM_PIPELINES = {
    5. # 'phone.pipelines.PhonePipeline': 300,
    6. 'phone.pipelines.putMySQLPipeline': 300,
    7. 'phone.pipelines.JsonWithEncodingPipeline': 400
    8. }
    9. mysql_host = '192.168.142.200' # 数据库IP地址
    10. mysql_user = 'root' # 数据库用户名
    11. mysql_passwd = '123456' # 数据库密码
    12. mysql_db = 'db01' # 数据库名
    13. mysql_tb = 'phonetable' # 数据表名
    14. mysql_port = 3306 # 数据库端口号
  7. 创建 start.py

    1. from scrapy import cmdline
    2. cmdline.execute("scrapy crawl getphone".split())
  8. 数据库

    1. 建立数据库

      1. create database db01;
    2. 数据库授权

      1. grant all privileges on db01.* 'root'@'%' identified by '123456';
    3. 建数据表

      1. create table phone (
      2. number bigint,
      3. price int,
      4. brand varchar(50)
      5. );
    4. 设置字符集编码

      1. 查看数据库字符集

        1. show create database db01;
      2. 修改数据库字符编码

        1. alter database db01 character set utf8;
      3. 查看数据表字符集

        1. show create table phone;
      4. 修改数据表字符编码

        1. alter table phone character set utf8;
  9. 运行项目
    直接运行 start.py

发表评论

表情:
评论列表 (有 0 条评论,252人围观)

还没有评论,来说两句吧...

相关阅读

    相关 scrapy多页面

    前言 使用scrapy的目的是方便爬虫人员通过scrapy框架编写简单的代码,提取需要爬取的网站上有用的数据,其框架底层已经对爬虫的过程做了大量的逻辑处理,而爬虫人员只需

    相关 scrapy提高速度

    scrapy在单机跑大量数据的时候,在对settings文件不进行设置的时候,scrapy的爬取速度很慢,再加上多个页面层级解析,往往导致上万的数据可能爬取要半个小时之久,这还