天天看点

10.5 Python导出爬取的数据至数据库并绘图分析

5、导出爬取的数据至数据库并绘图分析

1)导出爬取的数据至数据库

需求:

  • 将爬取到的数据导入数据库
  • 在添加爬取多页功能(第4节)的基础上进行后续开发

步骤:

(1)修改 pipeline.py 文件(输出到数据库)
  1. 获取数据连接
    • 导入sqlite3模块
    • 重写 Pipeline 的构造方法,获取数据库连接,并获取执行 SQL 语句的游标
  2. 使用游标将数据写入数据库
    • 重写 process_item(self, item, spider) 方法,在该方法中调用游标将数据插入数据库
  3. 关闭数据库资源
    • 重写 close_spider(self, spider) 方法,在该方法中关闭游标,关闭数据库连接
# -*- coding: utf-8 -*-
import sqlite3

class ZhipinspiderPipeline(object):
    # 1.获取数据连接
	def __init__(self):
		self.conn = sqlite3.connect('jobs.db')    # 连接数据库
		self.c = self.conn.cursor()               # 打开游标
        
		# 若数据库中没有表,则建立数据表
		self.c.execute('create table if not exists job_tb('
			+ 'id integer primary key autoincrement,'
			+ 'title,'
			+ 'salary,'
			+ 'company,'
			+ 'url,'
			+ 'work_addr,'
			+ 'industry,'
			+ 'company_size,'
			+ 'recruiter)')
	# 2.使用游标将数据写入数据库
	def process_item(self, item, spider):
		self.c.execute('insert into job_tb values(null, ?, ?, ?, ?, ?, ?, ?, ?)',
			(item['title'], item['salary'], item['company'], item['url'], item['work_addr'], item['industry'], 
			item['company_size'], item['recruiter']))
		self.conn.commit()

	# 3.关闭数据库资源
	def close_spider(self, spider):
		print('-------关闭数据库资源-------')
		self.c.close()
		self.conn.close()
           
(2)运行Spider项目
  • cmd 窗口下:

    F:

    cd F:\PycharmProjects\ZhipinSpider\ZhipinSpider

    scrapy crawl job_position

  • 数据库文件 jobs.db 文件:
    10.5 Python导出爬取的数据至数据库并绘图分析

2)使用Pygal绘图分析

需求:

  • 统计各行业所包含的岗位数量并用饼状图展示

步骤:

  1. 链接数据库读取招聘信息
  2. 统计各行业岗位数
  3. 创建、配置、生成 Pygal 图

创建 …\ZhipinSpider\ZhipinSpider\job_picture.py 文件:

# -*- coding: utf-8 -*-
import sqlite3, pygal

conn = sqlite3.connect('jobs.db')
cur = conn.cursor()

cur.execute("select * from job_tb")         # 执行查询

# 该字典{key:value,...}----{行业名:该行业岗位数,...}
job_dict = {}
for job in cur:
    industry = job[6]     # 获取所属行业
    # 若字典中已有该行业的信息,将其岗位数加一
    if industry in job_dict:
        job_dict[industry] += 1
    # 否则,该行业是第一次统计
    else:
        job_dict[industry] = 1

pie = pygal.Pie()        # 创建Pygal图(饼图)
other_num = 0            # 其他行业岗位数
for industry in job_dict.keys():
    # 如果该行业内就业岗位数小于5,归为其他行业
    if job_dict[industry] < 5:
        other_num += job_dict[industry]
    else:
        pie.add(industry, job_dict[industry])
pie.add('其他行业', other_num)

pie.title = '北京地区各行业的热门招聘分析图'
pie.legend_at_bottom = True

pie.render_to_file('job.svg')     # 输出到图片
           

用浏览器打开 job.svg 文件:

10.5 Python导出爬取的数据至数据库并绘图分析