找回密码
 立即注册→加入我们

QQ登录

只需一步,快速开始

搜索
热搜: 下载 VB C 实现 编写
查看: 2571|回复: 1

车型数据库

[复制链接]

307

主题

228

回帖

7303

积分

用户组: 真·技术宅

UID
2
精华
76
威望
291 点
宅币
5553 个
贡献
253 次
宅之契约
0 份
在线时间
944 小时
注册时间
2014-1-25
发表于 2017-7-15 16:03:23 | 显示全部楼层 |阅读模式

欢迎访问技术宅的结界,请注册或者登录吧。

您需要 登录 才可以下载或查看,没有账号?立即注册→加入我们

×
用最简单的爬虫获取汽车之家上各个型号汽车的配置
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import httplib
import random
import threading
import time
import sqlite3


dbpath = '/Users/baidu/Desktop/cardata'
params = []

def str2unicode(mustr):
    return unicode(mustr, 'utf-8')

def unicode2str(mstr):
    return mstr.encode('utf-8')

def runRequest(host, path, method, headers, body, ishttps=True, port=80):
    if ishttps:
        conn = httplib.HTTPSConnection(host)
    else:
        conn = httplib.HTTPConnection(host)
    conn.request(method, path, headers=headers, body=body)
    response = json.loads(conn.getresponse().read())
    return response


def doPost(id):
    try:
        response = runRequest('cars.app.autohome.com.cn',
                              '/cfg_v8.2.0/cars/speccompare.ashx?specids=%d' % id,
                              'GET',
                              {},
                              '',
                              ishttps=True) # id = 18~
        if len(response['result']['paramitems']) != 0:
            paramitems = response['result']['paramitems']
            cardict = {}
            for itemr in paramitems:
                for items in itemr['items']:
                    try:
                        key = items['name']
                        val = items['modelexcessids'][0]['value']
                        if val == u'-':
                            val = u''
                        cardict[key] = val
                    except:
                        pass
            seg1 = 'insert into cardata('
            seg2 = ' values('
            tups = []

            for item in cardict:
                seg1 = seg1 + '"' + item + '",'
                seg2 = seg2 + '?,'
                if type(cardict[item]) == int:
                    print cardict[item]
                tups.append(cardict[item])

            if seg1[-1] == ',':
                seg1 = seg1[: len(seg1) - 1]
            if seg2[-1] == ',':
                seg2 = seg2[: len(seg2) - 1]
            seg1 = seg1 + ')'
            seg2 = seg2 + ')'
            tups = tuple(tups)
            params.append({'sql' : seg1 + seg2, 'data' : tups})
            print '%d handled' % id
    except Exception as e:
        print e

def updateDb():
    while True:
        if len(params) != 0:
            try:
                dbconn = sqlite3.connect(dbpath)
                cursor = dbconn.cursor()
                for param in params:
                    cursor.execute(param['sql'], param['data'])
                dbconn.commit()
                cursor.close()
                dbconn.close()
            except Exception as e:
                print e
        time.sleep(10)

class threadPool(object):
    workers = 10
    jobs = []

    def __init__(self):
        for index in range(0, self.workers):
            self.jobs.append(None)

    def add(self, job):
        while True:
            for index in range(0, self.workers):
                if self.jobs[index] is None or not self.jobs[index].isAlive():
                    self.jobs[index] = job
                    job.start()
                    return
            time.sleep(0.5)

    def end(self):
        for job in self.jobs:
            if job is not None:
                job.join()

if __name__ == '__main__':
    lock = threading.Lock()
    pool = threadPool()
    threading.Thread(target=updateDb, args=()).start()
    # 18
    for num in range(18, 10000):
        pool.add(threading.Thread(target=doPost, args=(num,)))
    pool.end()
    time.sleep(10)
cardata.rar (1.11 MB, 下载次数: 1)

附件为sqlite数据库,下面来进行简单分析:
1.png 2.png 3.png 4.png 5.png 6.png 7.png 8.png
回复

使用道具 举报

1109

主题

1649

回帖

7万

积分

用户组: 管理员

一只技术宅

UID
1
精华
244
威望
743 点
宅币
24180 个
贡献
46222 次
宅之契约
0 份
在线时间
2294 小时
注册时间
2014-1-26
发表于 2017-7-20 09:53:18 | 显示全部楼层
这!是!python!
从前面几句import就让人感受到它的库的丰富
回复 赞! 靠!

使用道具 举报

QQ|Archiver|小黑屋|技术宅的结界 ( 滇ICP备16008837号 )|网站地图

GMT+8, 2024-3-19 10:19 , Processed in 0.036773 second(s), 31 queries , Gzip On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表