一、不写入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
}

 

数据库建设: 

结果:

pyspider 数据存入Mysql--Python3的更多相关文章

  1. php+phpspreadsheet读取Excel数据存入mysql

    先生成Excel模板,然后导入Excel数据到mysql,每条数据对应图片上传到阿里云 <?php /** * Created by PhpStorm. * User: Administrato ...

  2. Scrapy爬虫实例教程(二)---数据存入MySQL

    书接上回 实例教程(一) 本文将详细描述使用scrapy爬去左岸读书所有文章并存入本地MySql数据库中,文中所有操作都是建立在scrapy已经配置完毕,并且系统中已经安装了Mysql数据库(有权限操 ...

  3. 关于mapreducer 读取hbase数据 存入mysql的实现过程

    mapreducer编程模型是一种八股文的代码逻辑,就以用户行为分析求流存率的作为例子 1.map端来说:必须继承hadoop规定好的mapper类:在读取hbase数据时,已经有现成的接口 Tabl ...

  4. nodejs爬虫数据存入mysql

    node爬虫主要用的是三个插件 request cheerio mysql 废话不多说直接上代码 const request=require("request") const ch ...

  5. web项目数据存入mysql数据库中文乱码问题

    刚开始怀疑是项目中编码设置问题,发现在web.xml中已经有过设置:后来dubug显示数据在传输的过程中一切正常,怀疑是数据库编码问题,然后查看mysql编码: show variables like ...

  6. 【python 2.7】python读取json数据存入MySQL

    同上一篇,只是适配 CentOS+ python 2.7 #python 2.7 # -*- coding:utf-8 -*- __author__ = 'BH8ANK' import json im ...

  7. 【python 3.6】python读取json数据存入MySQL(二)

    在网上找到一个包含全国各省市经纬度的json文件,也可以通过上次的办法,解析json关键字,构造SQL语句,插入数据库. JSON文件格式如下: [ { "name": " ...

  8. 【python 3.6】python读取json数据存入MySQL(一)

    整体思路: 1,读取json文件 2,将数据格式化为dict,取出key,创建数据库表头 3,取出dict的value,组装成sql语句,循环执行 4,执行SQL语句 #python 3.6 # -* ...

  9. 将数据存入mysql中

    import pymysql import warnings # 忽略警告 warnings.filterwarnings("ignore") # 连接数据库 db = pymys ...

随机推荐

  1. 前端零基础入门:页面结构层HTML(3)

    搭建网页HTML结构 标签 标签 块级标签 和 行内标签 标签嵌套规则 和 div css 标签是一个区块容器标记, 之间是一个容器,可以包含段落,表格,图片等各种HTML元素. 标签没有实际意义,为 ...

  2. nginx 反向代理配置示例

    Nginx反向代理在生产环境中使用很多的. 场景1: 域名没有备案,可以把域名解析到香港一台云主机上,在香港云主机做个代理,而网站数据是在大陆的服务器上. server { listen ; serv ...

  3. 运行java程序的时候出现Exception in thread "main" java.lang.UnsupportedClassVersionError:

    1 Exception in thread "main" java.lang.UnsupportedClassVersionError: com/test/inherited/In ...

  4. 一个半吊子PM的反思

    故事之源 2019年3月,也就是2016级计算机学院的大三时,软件工程这门课程由选修转为专业必修课,而七个葫芦娃共聚罗杰老师的课堂,组成葫芦娃不想写代码小分队.面临着继承往届项目.完成指定项目和自选项 ...

  5. asp.net core session使用

    一.配置回话状态 Microsoft.AspNetCore.App metapackage 中包含的 Microsoft.AspNetCore.Session 包提供中间件来管理会话状态. 若要启用会 ...

  6. SpatiaLite, load spatial extension first

  7. 无废话centos+TDengine+Telegraf+Grafana入门

    一.安装TDengine:1.从官网https://www.taosdata.com/cn/getting-started/下载RPM包(tdengine-1.6.2.0-3.el7.x86_64.r ...

  8. grpc使用记录(三)简单异步服务实例

    目录 grpc使用记录(三)简单异步服务实例 1.编写proto文件,定义服务 2.编译proto文件,生成代码 3.编写服务端代码 async_service.cpp async_service2. ...

  9. Python之多态案例

    class Canvas: def draw_pic(self, shape): print('--start draw--') shape.draw(self) class Rectangle: d ...

  10. gitlib配置push后自动触发jenkins构建sonar扫描

    jenkins所用到的插件: Gitlab Hook Plugin 配置步骤 1.先进入gitlab的个人设置,生成api token 2.复制生成的访问令牌,打开jenkins的凭据,添加选择类型是 ...