栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python爬虫连接数据库【附上源码】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python爬虫连接数据库【附上源码】

文章内容
  • mysql部分
  • python部分
  • mysql中查询数据

mysql部分

首先先创建数据库python

create database python;

创建表yuanshi,这里列的数据类型需要根据爬虫获取的数据进行适当的修改

create table yuanshi(id nchar(5),info nvarchar(1000),picture nchar(100));

修改列数据类型的代码[注意修改的时候要把python对mysql的进程结束掉,否则就会卡住]

alter table 表名 modify column 列名 新的列的类型

查询mysql相关信息,为python连接做准备

  • 查询host
select user,host from mysql.user;
  • 大多数本机连接mysql都是localhost,即127.0.0.1
  • 本机密码为安装mysql时设置的密码,这里为123456
python部分
  • 爬虫部分直接上代码,本位重点讲解的是连接这一块
import re
import os
import os.path
import time
import json
import requests
import pymysql


name='曹喜滨'
url='https://www.cae.cn/cae/html/main/colys/63775817.html'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'}
r=requests.get(url,headers=headers)
r.encoding=r.apparent_encoding
print(r.status_code)
# 抓取照片,
pattern = r'
result = re.findall(pattern, r.text, re.I)
picUrl = r'http://www.cae.cn/cae/admin/upload/{0}'.format(result[0].replace(' ', r'%20'))
pattern = r'

(.+?)

' result = re.findall(pattern, r.text) intro = re.sub('()|( )|( )', '', ''.join(result))

这里先获取一个信息作为例子

  • 连接mysql数据库,并且把获得的数据以元组的形式导入到mysql中的表,就是前面mysql部分创建好的表。
class mysql_conn(object):
   # 魔术方法 ,初始化 , 构造函数
   def __init__(self):
       self.db = pymysql.connect(host='127.0.0.1',user='root',password='123456',port=3306,database='python')
       self.cursor = self.db.cursor()
   # 执行modify(修改)相关的操作
   def execute_modify_mysql(self,sql,data = None):
       self.cursor.execute(sql,data)
       self.db.commit()
   # 魔术方法 , 析构化 , 析构函数
   def __del__(self):
       self.cursor.close()
       self.db.close()

mc = mysql_conn()



data = (name,intro,picUrl)

sql = "insert into yuanshi(id,info,picture) values (%s,%s,%s);"
mc.execute_modify_mysql(sql,data = data)

到此爬取的数据就导入到mysql数据中了,现在我们可以到mysql数据库中查询yuanshi这个表的数据。

mysql中查询数据
  • 进入mysql命令框
# 进入python这个数据库
use python;
# 查看表格数据
select * from yuanshi;

这样子我们就可以在命令框看到我们爬虫得到的数据啦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1036982.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号