资讯专栏INFORMATION COLUMN

scrapy汽车之家车型的简单爬取

zhangfaliang / 3260人阅读

摘要:汽车之家车型的简单爬取名字自定义配置重新定义起始爬取点所有首字母按照首字母,组合对应的页面,压入根据,抓取页面定义默认的抓取函数品牌编号品牌名品牌品牌小类别品牌小类别对应的页面品牌小类别的编号品牌小类别名品牌小类别对应的页面的

汽车之家车型的简单爬取
spider

# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from mininova.items import carItem
import sys
reload(sys)
sys.setdefaultencoding("utf8")
class SplashSpider(scrapy.Spider):
    #spider名字
    name = "car_home"
    allowed_domains = ["autohome.com.cn"]
    start_urls = [
    ]
     # 自定义配置
    custom_settings = {
         "ITEM_PIPELINES": {
         "mininova.pipelines.CarPipeline": 300,
         }
    }
    def start_requests(self): #重新定义起始爬取点
        #所有首字母
        words = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
        #按照首字母,组合对应的页面,压入start_urls
        for word in words:
            self.start_urls.append("https://www.autohome.com.cn/grade/carhtml/"+word+".html") 
        #根据start_urls,抓取页面
        for url in self.start_urls:
            yield Request(url,meta={"word":word})
    #定义默认的抓取函数
    def parse(self, response): 
        print("url")
        print(response.url)
        word = response.meta["word"]
        car_cates = response.xpath("//dl").extract()
        brand_id = 0
        total_cars = []
        for brand_index in range(len(car_cates)):
            #品牌编号
            brand_num = brand_index + 1
            brand_num = str(brand_num)
            #品牌名
            brand = response.xpath("//dl["+brand_num+"]/dt/div[1]/a/text()").extract()[0]
            print("brand:"+brand)
            #品牌logo
            brand_logo_url = response.xpath("//dl["+brand_num+"]/dt//img[1]/@src").extract()[0]
            #品牌小类别
            brand_items = response.xpath("//dl["+brand_num+"]/dd//div[@class="h3-tit"]/a/text()").extract()
            #品牌小类别对应的页面
            brand_item_urls = response.xpath("//dl["+brand_num+"]/dd//div[@class="h3-tit"]/a/@href").extract()
            for brand_item_index in range(len(brand_items)):
                #品牌小类别的编号
                brand_item_num = brand_item_index + 1
                brand_item_num = str(brand_item_num)
                #品牌小类别名
                brand_item = brand_items[brand_item_index]
                #品牌小类别对应的页面的url
                brand_item_url = brand_item_urls[brand_item_index]
                print("brand_item:"+brand_item)
                print("brand_item_url:"+brand_item_url)
                #品牌小类别中的所有车
                cars = response.xpath("//dl["+brand_num+"]/dd//ul[@class="rank-list-ul"]["+brand_item_num+"]/li[@id]").extract()
                print("cars_count:"+str(len(cars)))
                for car_index in range(len(cars)):
                    car_num = car_index + 1
                    car_num = str(car_num)
                    #具体车的名称
                    name = response.xpath("//dl["+brand_num+"]/dd//ul[@class="rank-list-ul"]["+brand_item_num+"]/li[@id]["+car_num+"]/h4/a/text()").extract()[0]
                    #车对应的页面
                    url = response.xpath("//dl["+brand_num+"]/dd//ul[@class="rank-list-ul"]["+brand_item_num+"]/li[@id]["+car_num+"]/h4/a/@href").extract()[0]
                    #报价(最低价-最高价)
                    price = response.xpath("//dl["+brand_num+"]/dd//ul[@class="rank-list-ul"]["+brand_item_num+"]/li[@id]["+car_num+"]/div[1]/a/text()").extract()[0]
                    prices = price.split("-")
                    price_base = "万"
                    if len(prices) != 2:
                        max_price = "暂无"
                        min_price = "暂无"
                    else:
                        max_price = str(prices[1].replace(price_base,""))
                        min_price = str(prices[0])
                    print("car:"+name+" max_price:"+str(max_price)+" min_price:"+str(min_price)+" price_base:"+price_base)
                    car_item = carItem()
                    car_item["name"] = name
                    car_item["url"] = url
                    car_item["brand_item"] = brand_item
                    car_item["first_word"] = word
                    car_item["brand"] = brand
                    car_item["brand_logo_url"] = brand_logo_url
                    car_item["max_price"] = max_price
                    car_item["min_price"] = min_price
                    total_cars.append(car_item)
        return total_cars

item

# -*- coding: utf-8 -*-
import scrapy
class carItem(scrapy.Item):
    #具体车名
    name = scrapy.Field()
    #对应的介绍页面url
    url = scrapy.Field()
    #最高报价,单位(万)
    max_price = scrapy.Field()
    #最低报价,单位(万)
    min_price = scrapy.Field()
    #品牌名
    brand = scrapy.Field()
    #品牌logo
    brand_logo_url = scrapy.Field()
    #品牌小类别名
    brand_item = scrapy.Field()
    #品牌首字母
    first_word = scrapy.Field() 

mongo_car

from mininova.mongodb import Mongo
from mininova.settings import mongo_setting
class MongoCar():
    db_name = "car"
    brand_set_name = "brand"
    brand_item_set_name = "brand_item"
    car_set_name = "car"
    def __init__(self):
        self.db = Mongo(mongo_setting["mongo_host"],mongo_setting["mongo_port"],mongo_setting["mongo_user"],mongo_setting["mongo_password"])

    def insert(self,item):
        brand_where = {"name":item["brand"]}
        brand = self.brand_exist(self.db,brand_where)
        if brand == False:
            brand = {"name":item["brand"],"first_word":item["first_word"]}
            brand = self.insert_brand(self.db,brand)
            print("brand insert ok!")
        else:
            brand = {"name":item["brand"],"first_word":item["first_word"],"logo_url":item["brand_logo_url"]}
            brand = self.update_brand(self.db,brand_where,brand)
            print("brand_exist!")

        brand_item_where = {"name":item["brand_item"]}
        brand_item = self.brand_item_exist(self.db,brand_item_where)
        if brand_item == False:
            brand_item = {"name":item["brand_item"],"first_word":item["first_word"],"brand_id":brand["_id"]}
            brand_item = self.insert_brand_item(self.db,brand_item)
            print("brand_item insert ok!")
        else:
            print("brand_item_exist!")

        car_where = {"name":item["brand_item"],"name":item["name"]}
        car = self.car_exist(self.db,car_where)
        if car == False:
            car = {"name":item["name"],"url":item["url"],"max_price":item["max_price"],"min_price":item["min_price"],"first_word":item["first_word"],"brand_id":brand["_id"],"brand_item_id":brand_item["_id"]}
            car = self.insert_car(self.db,car)
            print("car insert ok!")
        else:
            print("car_exist!")
            


        if car != False:
            return True;
        else:
            return False;
    def update_brand(self,db,brand_where,brand):
        my_set = db.set(self.db_name,self.brand_set_name)
        my_set.update_one(brand_where,{"$set":brand})
        exist = my_set.find_one(brand_where)
        if(exist is None):
            return False
        else:
            return exist

    def brand_exist(self,db,brand):
        my_set = db.set(self.db_name,self.brand_set_name)
        exist = my_set.find_one(brand)
        if(exist is None):
            return False
        else:
            return exist

    def insert_brand(self,db,brand):
        my_set = db.set(self.db_name,self.brand_set_name)
        my_set.insert_one(brand)
        brand = my_set.find_one(brand)
        return brand

    def brand_item_exist(self,db,brand_item):
        my_set = db.set(self.db_name,self.brand_item_set_name)
        exist = my_set.find_one(brand_item)
        if(exist is None):
            return False
        else:
            return exist

    def insert_brand_item(self,db,brand_item):
        my_set = db.set(self.db_name,self.brand_item_set_name)
        my_set.insert_one(brand_item)
        brand = my_set.find_one(brand_item)
        return brand

    def car_exist(self,db,car):
        my_set = db.set(self.db_name,self.car_set_name)
        exist = my_set.find_one(car)
        if(exist is None):
            return False
        else:
            return exist

    def insert_car(self,db,car):
        my_set = db.set(self.db_name,self.car_set_name)
        my_set.insert_one(car)
        brand = my_set.find_one(car)
        return brand

pipeline

from mininova.settings import settings
import pymysql
import os
from mininova.db import Bookdb
from mininova.mongo_novel import MongoNovel
from mininova.mongo_car import MongoCar
import copy
class CarPipeline(object):   
    def process_item(self,item,spider):
        mongo_car = MongoCar()
        mongo_car.insert(item)
        print(item["name"])
        print("item insert ok!")

setting

mongo_setting = {
    "mongo_host" : "xxx.xxx.xxx.xxx",
    "mongo_port" : 27017,
    "mongo_user" : "username",
    "mongo_password" : "password"
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/43814.html

相关文章

  • 首次公开,整理12年积累博客收藏夹,零距离展示《收藏夹吃灰》系列博客

    摘要:时间永远都过得那么快,一晃从年注册,到现在已经过去了年那些被我藏在收藏夹吃灰的文章,已经太多了,是时候把他们整理一下了。那是因为收藏夹太乱,橡皮擦给设置私密了,不收拾不好看呀。 ...

    Harriet666 评论0 收藏0
  • 2016年,我对爬虫总结

    摘要:都说年末了,该给自己写写总结了。我现在做一些简单的爬虫都会用它。并且对数据的实时性要求较高,或者爬数据的时候封的太厉害了。对于这一类的爬虫。消息队列用于分发消息给某个爬虫节点。爬虫节点完成具体的爬虫,格式化爬虫数据。最后,感谢我的,谢谢 都说年末了,该给自己写写总结了。今天我想谈一谈的是我在公司这一年多里的负责的部分工作---爬虫。做了这么久的爬虫,是该写点什么,留下点什么。在我所负责...

    netmou 评论0 收藏0
  • Golang爬虫 爬取汽车之家 二手车产品库

    摘要:原文地址爬取汽车之家二手车产品库项目地址目标最近经常有人在耳边提起汽车之家,也好奇二手车在国内的价格是怎么样的,因此本次的目标站点是汽车之家的二手车产品库分析目标源一页共条含分页,但这个老产品库,在页后会存在问题,因此我们爬取页可以获取全 原文地址:爬取汽车之家 二手车产品库项目地址:https://github.com/go-crawler... 目标 最近经常有人在耳边提起汽车之家...

    sumory 评论0 收藏0
  • 爬虫学习之基于Scrapy网络爬虫

    摘要:不过不用担心,中有很多非常优秀的爬虫框架,比如我们接下来要学习到的。结合以上分析我们基本确定了本次爬虫的各个路线入口,接下来我们就开始通过程序来实现本次的目标。这里我们的目的是建立一种写爬虫的思路,而不在于怎么使用工具来爬数据。 概述 在上一篇文章《爬虫学习之一个简单的网络爬虫》中我们对爬虫的概念有了一个初步的认识,并且通过Python的一些第三方库很方便的提取了我们想要的内容,但是...

    BingqiChen 评论0 收藏0
  • 大话爬虫实践技巧

    摘要:图意淫爬虫与反爬虫间的对决数据的重要性如今已然是大数据时代,数据正在驱动着业务开发,驱动着运营手段,有了数据的支撑可以对用户进行用户画像,个性化定制,数据可以指明方案设计和决策优化方向,所以互联网产品的开发都是离不开对数据的收集和分析,数 showImg(https://segmentfault.com/img/remote/1460000013428119?w=539&h=337)...

    沈俭 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<