【python】简单爬虫制作(汽车之家&易车网报价爬虫)

首先交代背景,逗逼女朋友每个月要花费半天多的时间去汽车网上找三十多个城市、十多款车型的报价数据,而且他们部门其它人也要做这种繁琐的工作。我在网络卡屎的情况下帮她做了一回,我就打死都想写个程序把这种stupid的工作自动搞定。

上论坛一问,了解到原来这个叫爬虫,用python写比较简单。

那就开始学python,学爬虫。

其实没具体学python,或者对于爬虫的基本了解,直接看的这位博主的文章[Python]网络爬虫(六):一个简单的百度贴吧的小爬虫这是一个系列,花了点时间全看下来大概python照着模式写就够用了。

爬虫(Spider)的英文名其实很形象,整个互联网就是一张大网,而爬虫就像一种蜘蛛能够在这个网上爬来爬去,从一个网址跳转到另一个网站,抓取有价值的东西。

本程序所用python为3.4.2,系统为win7-64位,所有用到的插件请下载对应的版本

然后是网页的url分析,就是去多看多找,查看网页源码看是否能看到直接要的数据,如果找得到,可以直接使用正则表达正拿到数据,如果找不到,是js动态生成的,就去看源码里的js代码,搜索关键字url去找js拿去request的url,分析它的情况。

在本例中,汽车之家的数据是分析js代码所得url,通过url可直接请求得到城市与低价信息,用正则表达式获取

易车网数据可通过网页源码获取,所以其url就是浏览器地址上的url,通过url可请求到整个网页,再用正则表达式获取城市与价格信息

所有数据获取之后通过xlwr3和xlrd、xlutils保存到EXCEL中

源码

# -*- coding: utf-8 -*-  
#---------------------------------------  
#   程序:汽车之家&易车网最低价格抓取爬虫  
#   版本:0.1  
#   作者:top_along  
#   日期:2015-01-24  
#   语言:Python 3.4.2  
#   操作:直接打开
#   功能:抓取汽车之家上所有城市所需车型最低报价。  
#---------------------------------------  
   
import string, urllib.request
import re
import os
import xlwt3 as xlwt
import xlrd
from xlutils.copy import copy
import time


#from citys import citys


#汽车之家抓取函数
def qichezhijia(filename, cityId, specId):
    url = 'http://www.autohome.com.cn/ashx/AjaxDealerPrice.ashx?cityid=' \
          + str(cityId) + '00&specId=' + str(specId)
    m = urllib.request.urlopen(url).read()
    unicodePage = m.decode('gbk')

    reg = '<span class="font-price">([0-9\\.]+)</span>.*cityNameDefault=\'(.+)\';'
    items = re.search(reg, unicodePage, re.S)
    if items == None:
        return
    city = str(items.group(2))
    price = str(items.group(1))
    if city == "全国":
        return

    output = '[汽车之家]:   ' + city + '   数据正在写入...'
    print(output)
    saveToExcel(filename, cityId, specId, price, 0)
    return

#易车网抓取函数
def yichewang(filename, cityId, specId):
    url = 'http://car.bitauto.com/' + str(specId) \
          + '/baojia/c' + str(cityId) + '/'
    m = urllib.request.urlopen(url).read()
    unicodePage = m.decode('utf-8')

    regCity = '<ul class="area-sub"><li>(.+):</li><li>'
    items = re.search(regCity, unicodePage, re.S)
    if items == None:
        return   
    city = str(items.group(1))

    regPrice = '裸车售价:</label><span>([0-9\\.]+)万元</span></li><li><label>'
    prices = re.findall(regPrice, unicodePage, re.S)
    prices = set(prices)
    if len(prices) == 0:
        return
    price = prices.pop()
    for p in prices:
        if p < price:
            price = p
    
    output = '[易车网]:   ' + city + '   数据正在写入...'
    print(output)
    saveToExcel(filename, cityId, specId, price, 1)
    
    return


#保存数据到Excel
#city为城市名,specId为汽车id,两者决定Excel中的位置
#price为价格,sheetId为汽车之家与易车网之间两个sheet切换
def saveToExcel(filename, cityId, specId, price, sheetId):
    
    rdbook = xlrd.open_workbook(filename)
    rdsheet = rdbook.sheet_by_index(sheetId)
   
    city_col = rdsheet.col_values(0)
    try:
        row = city_col.index(cityId)
    except:
        return
    spec_row = rdsheet.row_values(0)
    try:
        col = spec_row.index(specId)
    except:
        return
    wtbook = copy(rdbook)
    wtsheet = wtbook.get_sheet(sheetId)
    wtsheet.write(row, col, price)
    wtbook.save(filename)

    return






def openExcel(filename):
    rdbook = xlrd.open_workbook(filename)

    #汽车之家
    rdsheet = rdbook.sheet_by_index(0)
    specs = rdsheet.row_values(0)
    specs = set(specs)
    specs.remove('')

    citys = rdsheet.col_values(0)
    citys = set(citys)
    citys.remove('')

    print('[汽车之家]数据准备写入')

    for city in citys:
        for spec in specs:
            qichezhijia(filename, city, spec)

    #易车网
    rdsheet = rdbook.sheet_by_index(1)
    specs = rdsheet.row_values(0)
    specs = set(specs)
    specs.remove('')
    print(specs)
    citys = rdsheet.col_values(0)
    citys = set(citys)
    citys.remove('')
    print(citys)

    print('[易车网]数据准备写入')
    
    for city in citys:
        for spec in specs:
            yichewang(filename, city, spec)
            
    return
    

def entry():
    print('汽车之家&易车网最低价格抓取爬虫')
    print('版本:0.1')
    print('作者:top_along')
    print('操作说明:')
    print('1、请确保当前文件夹下有文件“报价数据.xls”,且该文件未打开')
    print('2、“报价数据.xls”格式、扩展,请参见说明')
    print('3、请输入口令“阳娟阳娟变变变”开始')
    print('4、Enjoy...\n')
   
    
    keyword = input("请输入口令:\r\n")
    if keyword == "阳娟阳娟变变变":
        filename = u"报价数据.xls"
        openExcel(filename)
        input("输入任意字符回车退出")
    else:
        print("你真调皮...")
        time.sleep(2)
        print("你的电脑将在20秒内重启...")
        time.sleep(5)
        print("赶紧保存...")
        time.sleep(5)
        print("还有10秒...")
        time.sleep(5)
        print("5...")
        time.sleep(1)
        print("4...")
        time.sleep(1)
        print("3...")
        time.sleep(1)
        print("2...")
        time.sleep(1)
        print("1...")
        time.sleep(1)
        print("God bless you...")
        time.sleep(1)
        
#程序入口
entry()



保存制作exe请移驾

http://keliang.blog.51cto.com/3359430/661884

打包后闪退的情况是缺少部分插件,参见

http://blog.csdn.net/u014000832/article/details/39527981

    原文作者:top_along
    原文地址: https://blog.csdn.net/top_along/article/details/43272219
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞