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

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)
# 抓取照片,<img src="/cae/admin/upload/img/20200311095622881157087.jpg" style="width:150px;height:210px;"/>
pattern = r<img src="/cae/admin/upload/(.+)" style=
result = re.findall(pattern, r.text, re.I)
picUrl = rhttp://www.cae.cn/cae/admin/upload/{0}.format(result[0].replace( , r%20))
pattern = r<p>(.+?)</p>
result = re.findall(pattern, r.text)
intro = re.sub((<a.+</a>)|(&ensp;)|(&nbsp;), , .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;

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

经验分享 程序员 微信小程序 职场和发展