python 爬取古诗文存入mysql数据库的方法


Posted in Python onJanuary 08, 2020

使用正则提取数据,请求库requests,看代码,在存入数据库时,报错ERROR 1054 (42S22): Unknown column ‘title' in ‘field list'。原来是我写sql 有问题,sql = “insert into poem(title,author,content,create_time) values({},{},{},{})”.format(title, author,content,crate_time)
应该写成sql = “insert into poem(title,author,content,create_time) values('{}','{}','{}','{}')”.format(title, author,content,crate_time)

把插入的值放入引号中。

import datetime
import re
import pymysql
import requests
url = "https://www.gushiwen.org/"
headers = {
 'User-Agent': "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50"}
class Spiderpoem(object):
 conn = pymysql.Connect(host="localhost", port=3306, user="root", password='mysql', database='poem_data',
       charset="utf8")
 cs1 = conn.cursor()
 def get_requests(self, url, headers=None):
  """发送请求"""
  resp = requests.get(url, headers=headers)
  if resp.status_code == 200:
   # print(resp.request.headers)
   return resp.text
  return None
 def get_parse(self, response):
  """解析网页"""
  re_data = {
   "title": r'<div\sclass="sons">.*?<b>(.*?)</b>.*?</div>',
   "author": r'<p>.*?class="source">.*?<a.*?>(.*?)</a>.*?<a.*?>(.*?)</a>.*?</p>',
   "content": r'<div\sclass="contson".*?>(.*?)</div>'
  }
  titles = self.reg_con(re_data["title"], response)
  authors = self.reg_con(re_data["author"], response)
  poems_list = self.reg_con(re_data["content"], response)
  contents = list()
  for item in poems_list:
   ite = re.sub(r'<.*?>|\s', "", item)
   contents.append(ite.strip())
  for value in zip(titles, authors, contents):
   title, author, content = value
   author = "".join([author[0], '.', author[1]])
   poem = {
    "title": title,
    "author": author,
    "content": content
   }
   yield poem
 def reg_con(self, params, response):
  """正则匹配"""
  if not response:
   return "请求错误"
  param = re.compile(params, re.DOTALL) # re.DOTALL 匹配换行等价于re.S
  result = re.findall(param, response)
  return result
 @classmethod
 def save_data(cls, poem):
  title = poem.get("title")
  author = poem.get("author")
  content = poem.get("content")
  crate_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  sql = "insert into poem(title,author,content,create_time) values('{}','{}','{}','{}')".format(title, author,
                          content,
                          crate_time)
  count = cls.cs1.execute(sql)
  print(count)
  cls.conn.commit()
 def main(self):
  resp = self.get_requests(url, headers)
  for it in self.get_parse(resp):
   self.save_data(it)
  self.cs1.close()
  self.conn.close()
if __name__ == '__main__':
 Spiderpoem().main()

总结

以上所述是小编给大家介绍的python 爬取古诗文存入mysql数据库的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

Python 相关文章推荐
python读写二进制文件的方法
May 09 Python
Python使用 Beanstalkd 做异步任务处理的方法
Apr 24 Python
Python根据已知邻接矩阵绘制无向图操作示例
Jun 23 Python
Python 获取div标签中的文字实例
Dec 20 Python
详解python和matlab的优势与区别
Jun 28 Python
python 公共方法汇总解析
Sep 16 Python
Python3并发写文件与Python对比
Nov 20 Python
python科学计算之narray对象用法
Nov 25 Python
Python @property装饰器原理解析
Jan 22 Python
python实现梯度法 python最速下降法
Mar 24 Python
Python通过Pillow实现图片对比
Apr 29 Python
Python的logging模块基本用法
Dec 24 Python
基于python3抓取pinpoint应用信息入库
Jan 08 #Python
Python PyInstaller安装和使用教程详解
Jan 08 #Python
关于Pytorch的MLP模块实现方式
Jan 07 #Python
PyTorch 普通卷积和空洞卷积实例
Jan 07 #Python
Pytorch中膨胀卷积的用法详解
Jan 07 #Python
Python urlopen()和urlretrieve()用法解析
Jan 07 #Python
简单了解Django ORM常用字段类型及参数配置
Jan 07 #Python
You might like
php生成zip压缩文件的方法详解
2013/06/09 PHP
php约瑟夫问题解决关于处死犯人的算法
2015/03/23 PHP
PHP实现根据时间戳获取周几的方法
2016/02/26 PHP
thinkphp3.x连接mysql数据库的方法(具体操作步骤)
2016/05/19 PHP
php二维数组按某个键值排序的实例讲解
2019/02/15 PHP
一些不错的js函数ajax
2008/08/20 Javascript
删除条目时弹出的确认对话框
2014/06/05 Javascript
jQuery中unwrap()方法用法实例
2015/01/16 Javascript
js实现跨域的方法实例详解
2015/06/24 Javascript
vue-cli如何引入bootstrap工具的方法
2017/10/19 Javascript
详解如何在vscode里面调试js和node.js的方法步骤
2018/12/24 Javascript
vue实现扫码功能
2020/01/17 Javascript
vue 自定义组件的写法与用法详解
2020/03/04 Javascript
用python找出那些被“标记”的照片
2017/04/20 Python
Python利用递归和walk()遍历目录文件的方法示例
2017/07/14 Python
python2.7无法使用pip的解决方法(安装easy_install)
2018/04/03 Python
python实现在pandas.DataFrame添加一行
2018/04/04 Python
为什么str(float)在Python 3中比Python 2返回更多的数字
2018/10/16 Python
python3连接mysql获取ansible动态inventory脚本
2020/01/19 Python
解决TensorFlow模型恢复报错的问题
2020/02/06 Python
python 3.8.3 安装配置图文教程
2020/05/21 Python
python关于倒排列的知识点总结
2020/10/13 Python
windows+vscode安装paddleOCR运行环境的步骤
2020/11/11 Python
加拿大领先的冒险和户外零售商:Atmosphere
2017/12/19 全球购物
大学生毕业鉴定
2014/01/31 职场文书
婚礼主持结束词
2014/03/13 职场文书
内勤主管岗位职责
2014/04/03 职场文书
超市周年庆活动方案
2014/08/16 职场文书
2014年干部培训工作总结
2014/12/17 职场文书
暂住证证明
2015/06/19 职场文书
董事长助理工作总结2015
2015/07/23 职场文书
中学生打架检讨书之500字
2019/08/06 职场文书
Nginx反向代理学习实例教程
2021/10/24 Servers
Python调用腾讯API实现人脸身份证比对功能
2022/04/04 Python
vue修饰符.capture和.self的区别
2022/04/22 Vue.js
六个好看实用的 HTML + CSS 后台登录入口页面
2022/04/28 HTML / CSS