5、導出爬取的資料至資料庫并繪圖分析
1)導出爬取的資料至資料庫
需求:
- 将爬取到的資料導入資料庫
- 在添加爬取多頁功能(第4節)的基礎上進行後續開發
步驟:
(1)修改 pipeline.py 檔案(輸出到資料庫)
- 擷取資料連接配接
- 導入sqlite3子產品
- 重寫 Pipeline 的構造方法,擷取資料庫連接配接,并擷取執行 SQL 語句的遊标
- 使用遊标将資料寫入資料庫
- 重寫 process_item(self, item, spider) 方法,在該方法中調用遊标将資料插入資料庫
- 關閉資料庫資源
- 重寫 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 檔案:
2)使用Pygal繪圖分析
需求:
- 統計各行業所包含的崗位數量并用餅狀圖展示
步驟:
- 連結資料庫讀取招聘資訊
- 統計各行業崗位數
- 建立、配置、生成 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 檔案: