python 爬取古诗文存入mysql数据库的方法
作者:go_flush 发布时间:2024-01-28 13:35:26
标签:python,爬取,mysql
使用正则提取数据,请求库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数据库的方法网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
来源:https://blog.csdn.net/weixin_44224529/article/details/103841355


猜你喜欢
- 本文实例讲述了python飞机大战pygame游戏框架搭建操作。分享给大家供大家参考,具体如下:目标明确主程序职责实现主程序类准备游戏精灵组
- 建立资料表:Step1首先开启phpmyadmin,进入wordpress资料库中,并新增一个wp_gbook的资料表与栏位数目8。Step
- 问题起因最近要将一个文本分割成好几个topic,每个topic设计一个regressor,各regressor是相互独立的,最后汇总所有to
- 变量命名在《初识永远强大的函数》一文中,有一节专门讨论“取名字的学问”,就是有关变量名称的问题,本温故而知新的原则,这里要复习:名称格式:(
- 问题Go语言在编译时不会将配置文件这类第三方文件打包进二进制文件中它既受当前路径的影响,也会因所填写的不同而改变,并非是绝对可靠的解决命令行
- 看Python简明教程,学习使用print打印字符串,试了下打印中文,不行。编辑环境:IDLE上网搜了下解决办法,各种说法,试了两种:pri
- python读文件操作1. read三种不同的方式f = open('hello.txt') #'hello.txt
- ERROR 1819 (HY000): Your password does not satisfy the current policy
- Python字典的key都可以是什么答一个对象能不能作为字典的key,就取决于其有没有__hash__方法。所以所有python自带类型中,
- Inside君整理了一份最新基于MySQL 5.6和5.7的配置文件模板,基本上可以说覆盖90%的调优选项,用户只需根据自己的服务器配置稍作
- 1.什么是面向对象面向对象(oop)是一种抽象的方法来理解这个世界,世间万物都可以抽象成一个对象,一切事物都是由对象构成的。应用在编程中,是
- 我就废话不多说,咱直接看代码吧!tf.transposetranspose( a, perm=None,  
- 本文实例为大家分享了opencv实现回形遍历像素算法的具体代码,供大家参考,具体内容如下代码实现# -*- coding:utf-8 -*-
- python封装简介1.效果图:对比一:对比二:2.学习来源代码:# 封装是面向对象的三大特性之一# 封装指的是隐藏对象中一些不希望被外部所
- 本文实例讲述了Python 面向对象静态方法、类方法、属性方法知识点。分享给大家供大家参考,具体如下:(1)静态方法--》-@staticm
- 1.linux下启动mysql的命令:mysqladmin start/ect/init.d/mysql start (前面为mysql的安
- 本文实例讲述了Python操作多维数组输出和矩阵运算。分享给大家供大家参考,具体如下:在许多编程语言中(Java,COBOL,BASIC),
- 前言为了避免代码泄露的风险,我们往往需要对代码进行加密,PyArmor 是一个用于加密和保护 Python 脚本的工具。它能够在运行时刻保护
- 1.根据id获取元素document.getElementById("id属性的值");返回值是一个元素对象案例:点击按
- 本文实例讲述了js实现文本框宽度自适应文本宽度的方法。分享给大家供大家参考。具体如下:一个会随着输入文本框的字符多少而自动增加宽度的JS代码