一、不写入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. nginx.conf 配置解析之 server配置

    server{} 包含在http{}内部,每一个server{}都是一个虚拟主机(站点) 以下为nginx.conf配置文件中server{  }部分的内容. server { listen ; // ...

  2. 「SDOI2014」旅行(信息学奥赛一本通 1564)(洛谷 3313)

    题目描述 S国有N个城市,编号从1到N.城市间用N-1条双向道路连接,满足从一个城市出发可以到达其它所有城市.每个城市信仰不同的宗教,如飞天面条神教.隐形独角兽教.绝地教都是常见的信仰. 为了方便,我 ...

  3. Spatiotemporal continuous estimates of PM2.5 concentrations in China, 2000–2016: A machine learning method with inputs from satellites, chemical transport model, and ground observations

    写在前面 首先,看完查了一下这个期刊 Environment International,是1区的文章,影响因子7.297!不愧是优秀的期刊,文章质量很高,内容很丰富. 内容 主要是PM25反演,利用 ...

  4. sql注入用<>绕过被过滤的select ——百度杯9月第二场SQL

    题目提示SQL注入,打开源代码发现<!--SELECT * FROM info WHERE id=1--> 尝试union select 1,2,3提示inj code! 经过多次尝试之后 ...

  5. spring boot整合websocket之使用自带tomcat启动项目报错记录

    项目中用到websocket,就将原来写好的websocket工具类直接拿来使用,发现前端建立连接的时候报404,经查找发现是因为原来用的是配置的外部tomcat启动,这次是spring boot自带 ...

  6. Gevent简明教程

    Gevent简明教程  发表于 2015-11-28 |  分类于 技术| |  阅读次数 5159 前述 进程 线程 协程 异步 并发编程(不是并行)目前有四种方式:多进程.多线程.协程和异步. 多 ...

  7. spring mvc中添加对Thymeleaf的支持

    一.下载Thymeleaf 官方下载地址:https://dl.bintray.com/thymeleaf/downloads/thymeleaf/ 我下载的是最新的3.0.11版本 把包里的jar包 ...

  8. layer.confirm 防止post重复提交

    layer.confirm("确定对该资源单的价格"+isa+value+"元吗!", function(index, layero){ $(layero).f ...

  9. PowerMock框架讲解及使用

    为什么要使用PowerMock 现如今比较流行的Mock工具如jMock .EasyMock .Mockito等都有一个共同的缺点:不能mock静态.final.私有方法等.而PowerMock能够完 ...

  10. 移除 WordPress 自动加载的 jQuery,使用自定义 jQuery 版本

    WordPress 使用的 jQuery 版本由于需要考虑到很多安全稳定的因素,所以一般不会使用最新版本的 jQuery, 可以通过以下方式移除 WordPress 自定加载的 jQuery,并加载自 ...