04 python爬虫 (数据库)
- MySQL是一种关系数据库管理系统,是一种开源软件
4、MySQL
- 进入命令
- mysql –h127.0.0.1 –uroot –p211574 –P3306
- MySQL数据库的安装
- https://www.jb51.net/article/167782.htm
- 注意事项
- 端口号: 3306
- 默认用户: root
- 字符集:默认字符集latin1,应设置为gbk或utf-8
- 启动MySQL服务: net start mysql80
- 登录MySQL服务器: mysql –h127.0.0.1 –uroot –proot –P3306
- 关闭MySQL服务: net stop mysql80
- MySQL支持选择在该类型关键字后面的括号内指定整数值的显示宽度(例如,INT(4))。显示宽度并不限制可以在列内保存的值的范围,也不限制超过列的指定宽度的值的显示
- 常用的SQL语句
- SQL语言包含4个部分
- 数据定义语言(如create,drop,alter等语句)4
- 数据查询语言(select语句)
- 数据操纵语言(insert,delete,update语句)
- 数据控制语言(如grant,revoke,commit,rollback等语句)
- 数据操纵语言针对表中的数据,而数据定义语言针对数据库或表
-
# 09-Python与MySQL进行交互
-
import mysql.connector
-
-
# 创建连接对象
-
conn = mysql.connector.connect(host='localhost',user='root',passwd='123456',
-
database='test',auth_plugin='mysql_native_password')
-
-
# print(conn)
-
mycursor = conn.cursor()
-
-
# 编写sql语句
-
sql = 'insert into dept (deptno,dname,loc) values (%s,%s,%s)'
-
val = (50,'开发部','北京')
-
-
# 执行sql语句
-
mycursor.execute(sql,val)
-
-
# 提交
-
conn.commit()
-
print(mycursor.rowcount,'记录插入成功')
- SQL语句语法
- 数据定义语言
- 创建数据库 create database 数据库名
- 显示所有数据库 show databases
- 使用指定数据库 use 数据库名
- 删除表 drop table 表名
- 删除数据库 drop database 数据库名
- 数据定义语言
- 修改表结构
- 增加列 alter table 表名 add 列名 数据类型(长度)
- 修改列的数据类型 alter table 表名 modify 列名 数据类型(长度)
- 修改列的名称 alter table 表名 change 原列名 新列名 数据类型(长度)
- 删除列 alter table 表名 drop 列名
-
# 修改操作
-
import mysql.connector
-
-
# 创建连接对象
-
conn = mysql.connector.connect(host='localhost',user='root',passwd='211574',
-
database='test',auth_plugin='mysql_native_password')
-
-
# print(conn)
-
mycursor = conn.cursor()
-
-
# 编写sql语句
-
sql = 'update dept set dname = "Python部门" where deptno = 50'
-
-
-
# 执行sql语句
-
mycursor.execute(sql)
-
conn.commit()
-
print(mycursor.rowcount,'修改成功')
- 数据操作语言
- 向表中插入数据 insert into 表名 [(字段列表)] values (值列表)
- 修改表中的数据 update 表名 set 字段1=值1,字段2=值2..... [where]
- 删除表中的数据 delete from 表名 [where]
- 数据查询语言
- 单表查询 select .... from 表名 [where] (where 是定区间)... [group by] ...[having]...[order by asc/desc] (order排序)
- 模糊查询
- 只能与字符型一起使用的like关键字 # select * from emp where ename like '%M%';
- 区间范围的 between... and... # select * from emp where sal between 2000 and 3000 order by sal desc;
- 在给定的值中进行选择的 in # select * from emp where job in ('CLERK','MANAGER') order by job;
- 分组函数 count() sum() avg() max() min()
- 数据查询语言 select ...from 表1 inner join 表2 on 连接条件 ..[where]....
- 表连接查询 select ...from 表1 left/right join 表2 on 连接条件 ..[where]....
5、Python与MySQL的交互操作
- Python与MySQL进行交互
- 安装第三方库
- mysql-connector
- 常用操作
- 插入数据 insert
- 查询数据 select
- 更新数据 update
- 创建数据库连接
- connect( host , user , passwd , database)
- 插入数据操作步骤
- 获取连接对象
- 获取cursor对象
- 编写SQL语句
- 执行SQL语句
- 提交事务
- 批量插入数据操作步骤
- 获取连接对象
- 获取cursor对象
- 编写SQL语句
- 使用列表赋值
- 调用executemany()执行sql语句
- 提交事务
- 查询操作步骤
- 获取连接对象
- 获取cursor对象
- 编写SQL语句
- 执行SQL语句
- 调用fetchall()方法获取返回结果,结果为列表类型
- 遍历列表
- 更新数据与删除数据
- 获取连接对象
- 获取cursor对象
- 编写SQL语句
- 执行SQL语句
- 提交事务
链家房价数据:
-
import requests
-
from bs4 import BeautifulSoup
-
import mysql.connector
-
-
class Lianjiaspider():
-
mydb = mysql.connector.connect(host='localhost',user='root',passwd = '211574',database = 'test',auth_plugin = 'mysql_native_password')
-
mycursor = mydb.cursor() # 指针
-
-
def __init__(self):
-
self.url = 'https://chongqing.anjuke.com/sale/jiangbei/p{0}/?from=HomePage_TopBar'
-
self.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'}
-
-
def send_request(self,url):
-
resp = requests.get(url,headers=self.headers)
-
if resp.status_code == 200:
-
return resp
-
-
def parse_html(self,resp):
-
lst = []
-
html = resp.text
-
bs = BeautifulSoup(html,'lxml')
-
section = bs.find('section',class_='list')
-
section_list = section.find_all('div',class_='property')
-
print(len(section_list))
-
for item in section_list:
-
# print(item,'\n')
-
title = item.find('div',class_="property-content-title").text
-
print(title)
-
house_info = item.find('div',class_='property-content-info').text
-
print(house_info)
-
# position_info = item.find('div',class_='positioninfo').text
-
# deal_date = item.find('div',class_='dealdate').text
-
# number = item.find('span',class_='number').text '万'
-
# unit_price = item.find('div',class_='unitprice').text
-
# deal_housetxt = item.find('span',class_='dealhousetxt')
-
# if deal_housetxt != None:
-
# deal_housetxt = deal_housetxt.text
-
# else:
-
# deal_housetxt =''
-
# span = item.find('span',class_='dealcycletxt')
-
# span_list = span.find_all('span')
-
# agent_name = item.find('a',class_='agent_name').text
-
#
-
# lst.append((title,house_info,position_info,deal_date,number,unit_price,deal_housetxt,span_list[0].text,span_list[1].text,agent_name))
-
# print(lst)
-
# self.save(self,lst)
-
-
def save(self,lst):
-
sql = 'insert into tb_lianjia (title,house_info,position_info,deal_data,total_price,unit_price,deal_house_txt,deal_money,deal_date,agent_name) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'
-
self.mycursor.executemany(sql,lst)
-
self.mydb.commit()
-
-
def start(self):
-
for i in range(1,2):
-
full_url = self.url.format(i)
-
resp = self.send_request(full_url)
-
# print(resp.text)
-
self.parse_html(resp)
-
-
pass
-
-
if __name__ == '__main__':
-
lianjia = Lianjiaspider()
-
lianjia.start()
6、MongoDB简介
- 启动方式:G:\00-software\mongodb_v4.0.3\bin\mongod.exe --dbpath G:\00-software\mongodb_v4.0.3\data\db
- 先点:G:\00-software\mongodb_v4.0.3 中的start,再点 bin中的mongo
- user: "admin", pwd: "123456", roles: ["root"]
- 网络连接错误处理方式:https://blog.csdn.net/qq_44163269/article/details/106583276?
- use admin
- db.createUser({user:"admin", pwd: "123456", roles: ["root"]})
- db.auth("admin","123456")
连接MongoDB
-
import pymongo
-
-
# 连接到服务器
-
client = pymongo.MongoClient('localhost',27017)
-
-
# 获取要操作的数据库
-
# db = client.school
-
db = client['school']
-
# print(db)
-
-
# 获取要操作的集合
-
# collection = db.student
-
collection = db['student']
-
# print(collection)
-
-
# 执行插入操作
-
# stu = {'name':'张一个一个地','age':20,'gender':'女'}
-
# collection.insert_one(stu)
-
-
# 一次插入多条数据
-
lst = [
-
{'name':'王二二','age':23},
-
{'name':'张三三','age':26},
-
{'name':'李思思','gender':'女'}
-
]
-
collection.insert_many(lst)
是一个高性能,开源,无模式的文档型数据库,是当前 NOSQL数据库产品中最热门的一种。它在许多场景下用于替代传统的关系型数据库或键值对存储方式。
- MongoDB是用C 开发的。它是一个基于分布式文件存储的开源数据库系统。
- MongoDB将数据存储为一个文档,数据结构由键值(key-value)对组成。
- MongoDB文档类似JSON对象。
- 字段值可以包含其他文档、数组及文档数组。
MongoDB的安装:
- 绿色版无需安装直接解压就可以使用 (64位,32位可通用)
- MongoDB的GUI
启动服务:
- 创建数据库目录 如/data/db
- 执行 mongd –dbpath d:/data/db
collection与table的差异:
- table: 有结构,行遵循结构
- collection
- 文档无结构
- 文档相互独立没有固定结构
Object ID:
- 每个文档都有一个属性,为_id,保证每个文档的唯一性
- 可以自己去设置_id插入文档
- 如果没有提供,那么MongoDB为每个文档提供了一个独特的_id,类型为objectID
- objectID是一个12字节的十六进制数
- 前4个字节为当前时间戳
- 接下来3个字节的机器ID
- 接下来的2个字节中MongoDB的服务进程id
- 最后3个字节是简单的增量值
- 排序操作:
- 语法: >db.COLLECTION_NAME.find().sort({KEY:1})
- db.collection_lianjia.find().sort({'position':1})
链家房价数据(MongoDB)
-
import requests
-
from bs4 import BeautifulSoup
-
import pymongo
-
-
class Lianjiaspider():
-
-
def __init__(self):
-
self.url = 'https://chongqing.anjuke.com/sale/jiangbei/p{0}/?from=HomePage_TopBar'
-
self.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36'}
-
-
def send_request(self,url):
-
resp = requests.get(url,headers=self.headers)
-
if resp.status_code == 200:
-
return resp
-
-
def parse_html(self,resp):
-
lst = []
-
html = resp.text
-
bs = BeautifulSoup(html,'lxml')
-
section = bs.find('section',class_='list')
-
section_list = section.find_all('h3')
-
print(section_list)
-
print(len(section_list))
-
for item in section_list:
-
print(item,'\n')
-
total = item.find('p', class_='property-price-total')
-
print(total)
-
-
# title = item.find('div',class_="property-content-title").text
-
# print(title)
-
-
title = item.find('div', class_="property-content-title").text
-
house_info = item.find('div',class_='houseinfo').text
-
position_info = item.find('div',class_='positioninfo').text
-
deal_date = item.find('div',class_='dealdate').text
-
number = item.find('span',class_='number').text '万'
-
unit_price = item.find('div',class_='unitprice').text
-
deal_housetxt = item.find('span',class_='dealhousetxt')
-
if deal_housetxt != None:
-
deal_housetxt = deal_housetxt.text
-
else:
-
deal_housetxt =''
-
span = item.find('span',class_='dealcycletxt')
-
span_list = span.find_all('span')
-
agent_name = item.find('a',class_='agent_name').text
-
-
lst.append({'title':title,
-
'house_info':house_info,
-
'position_info':position_info,
-
'deal_data':deal_date,
-
'total_price':number,
-
'unit_price':unit_price,
-
'deal_house_txt':deal_housetxt,
-
'deal_money':span_list[0].text,
-
'deal_date':span_list[1].text,
-
'agent_name':agent_name})
-
-
# print(lst)
-
self.save(self,lst)
-
-
def save(self,lst):
-
# 获取连接对象
-
client = pymongo.MongoClient('localhost',27017)
-
-
# 获取要操作的数据库
-
db = client['lianjia']
-
-
# 获取collection
-
collection = db['collection_lianjia']
-
collection.insert_many(lst)
-
-
def start(self):
-
for i in range(1,2):
-
full_url = self.url.format(i)
-
resp = self.send_request(full_url)
-
# print(resp.text)
-
self.parse_html(resp)
-
-
pass
-
-
if __name__ == '__main__':
-
lianjia = Lianjiaspider()
-
lianjia.start()
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhgkehah
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13