pyspider 數據存入Mysql--Python3


一、不寫入Mysql

以爬取哪兒網為例。

以下為腳本:

from pyspider.libs.base_handler import *


class Handler(BaseHandler):
    crawl_config = {
    }

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('https://travel.qunar.com/travelbook/list.htm', callback=self.index_page, validate_cert=False)

    @config(age=100 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('li > .tit > a').items():
            self.crawl(each.attr.href, callback=self.detail_page, validate_cert=False, fetch_type='js')
        next = response.doc('.next').attr.href
        self.crawl(next, callback=self.index_page)

    @config(priority=2)
    def detail_page(self, response):
        return {
            "url": response.url,
            "title": response.doc('#booktitle').text(),
            "date": response.doc('.when .data').text(),
            "day": response.doc('.howlong .data').text(),
            "who": response.doc('.who .data').text(),
            "text": response.doc('#b_panel_schedule').text(),
            "image": response.doc('.cover_img').text(),
        }

  這個腳本里只是單純的將結果打印在pyspider 的web ui中,並沒有存到其它地方。

二、存入Mysql中

插入數據庫的話,需要我們在調用它之前定義一個save_in_mysql函數。 並且需要將連接數據庫等初始化放在__init__函數中

注: pymysql.connect('localhost', '賬號', '密碼', '數據庫', charset='utf8')

 

  # 連接數據庫
    def __init__(self):
        self.db = pymysql.connect('localhost', 'root', 'root', 'qunar', charset='utf8')

    def save_in_mysql(self, url, title, date, day, who, text, image):
        try:
            cursor = self.db.cursor()
            sql = 'INSERT INTO qunar(url, title, date, day, who, text, image) \
            VALUES (%s, %s , %s, %s, %s, %s, %s)'   # 插入數據庫的SQL語句
            print(sql)
            cursor.execute(sql, (url, title, date, day, who, text, image))
            print(cursor.lastrowid)
            self.db.commit()
        except Exception as e:
            print(e)
            self.db.rollback()

 

然后在detail_page中調用save_in_mysql函數:

@config(priority=2)
    def detail_page(self, response):
        url = response.url
        title = response.doc('title').text()
        date = response.doc('.when .data').text()
        day = response.doc('.howlong .data').text()
        who = response.doc('.who .data').text()
        text = response.doc('#b_panel_schedule').text()[0:100].replace('\"', '\'', 10)
        image = response.doc('.cover_img').attr.src

     # 插入數據庫 self.save_in_mysql(url, title, date, day, who, text, image) return { "url": response.url, "title": response.doc('title').text(), "date": response.doc('.when .data').text(), "day": response.doc('.howlong .data').text(), "who": response.doc('.who .data').text(), "text": response.doc('#b_panel_schedule').text(), "image": response.doc('.cover_img').attr.src }

 

三、完整代碼、數據庫建設及運行結果 (代碼可直接跑)

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2019-07-02 21:37:08
# Project: qunar

from pyspider.libs.base_handler import *
import pymysql


class Handler(BaseHandler):
    crawl_config = {
    }

    # 連接數據庫
    def __init__(self):
        self.db = pymysql.connect('localhost', 'root', 'root', 'qunar', charset='utf8')

    def save_in_mysql(self, url, title, date, day, who, text, image):
        try:
            cursor = self.db.cursor()
            sql = 'INSERT INTO qunar(url, title, date, day, who, text, image) \
            VALUES (%s, %s , %s, %s, %s, %s, %s)'   # 插入數據庫的SQL語句
            print(sql)
            cursor.execute(sql, (url, title, date, day, who, text, image))
            print(cursor.lastrowid)
            self.db.commit()
        except Exception as e:
            print(e)
            self.db.rollback()

    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl('http://travel.qunar.com/travelbook/list.htm', callback=self.index_page)

    @config(age=10 * 24 * 60 * 60)
    def index_page(self, response):
        for each in response.doc('li > .tit > a').items():
            self.crawl(each.attr.href, callback=self.detail_page, fetch_type='js')
        next_url = response.doc('.next').attr.href
        self.crawl(next_url, callback=self.index_page)

    @config(priority=2)
    def detail_page(self, response):
        url = response.url
        title = response.doc('title').text()
        date = response.doc('.when .data').text()
        day = response.doc('.howlong .data').text()
        who = response.doc('.who .data').text()
        text = response.doc('#b_panel_schedule').text()[0:100].replace('\"', '\'', 10)
        image = response.doc('.cover_img').attr.src

     # 存入數據庫 self.save_in_mysql(url, title, date, day, who, text, image) return { "url": response.url, "title": response.doc('title').text(), "date": response.doc('.when .data').text(), "day": response.doc('.howlong .data').text(), "who": response.doc('.who .data').text(), "text": response.doc('#b_panel_schedule').text(), "image": response.doc('.cover_img').attr.src }

 

數據庫建設: 

 

結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM