• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

04 python爬虫 (数据库)

武飞扬头像
处女座_三月
帮助1

  • 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等语句)
    • 数据操纵语言针对表中的数据,而数据定义语言针对数据库或表
  1.  
    # 09-Python与MySQL进行交互
  2.  
    import mysql.connector
  3.  
     
  4.  
    # 创建连接对象
  5.  
    conn = mysql.connector.connect(host='localhost',user='root',passwd='123456',
  6.  
    database='test',auth_plugin='mysql_native_password')
  7.  
     
  8.  
    # print(conn)
  9.  
    mycursor = conn.cursor()
  10.  
     
  11.  
    # 编写sql语句
  12.  
    sql = 'insert into dept (deptno,dname,loc) values (%s,%s,%s)'
  13.  
    val = (50,'开发部','北京')
  14.  
     
  15.  
    # 执行sql语句
  16.  
    mycursor.execute(sql,val)
  17.  
     
  18.  
    # 提交
  19.  
    conn.commit()
  20.  
    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  列名
  1.  
    # 修改操作
  2.  
    import mysql.connector
  3.  
     
  4.  
    # 创建连接对象
  5.  
    conn = mysql.connector.connect(host='localhost',user='root',passwd='211574',
  6.  
    database='test',auth_plugin='mysql_native_password')
  7.  
     
  8.  
    # print(conn)
  9.  
    mycursor = conn.cursor()
  10.  
     
  11.  
    # 编写sql语句
  12.  
    sql = 'update dept set dname = "Python部门" where deptno = 50'
  13.  
     
  14.  
     
  15.  
    # 执行sql语句
  16.  
    mycursor.execute(sql)
  17.  
    conn.commit()
  18.  
    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语句
    • 提交事务

链家房价数据:

  1.  
    import requests
  2.  
    from bs4 import BeautifulSoup
  3.  
    import mysql.connector
  4.  
     
  5.  
    class Lianjiaspider():
  6.  
    mydb = mysql.connector.connect(host='localhost',user='root',passwd = '211574',database = 'test',auth_plugin = 'mysql_native_password')
  7.  
    mycursor = mydb.cursor() # 指针
  8.  
     
  9.  
    def __init__(self):
  10.  
    self.url = 'https://chongqing.anjuke.com/sale/jiangbei/p{0}/?from=HomePage_TopBar'
  11.  
    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'}
  12.  
     
  13.  
    def send_request(self,url):
  14.  
    resp = requests.get(url,headers=self.headers)
  15.  
    if resp.status_code == 200:
  16.  
    return resp
  17.  
     
  18.  
    def parse_html(self,resp):
  19.  
    lst = []
  20.  
    html = resp.text
  21.  
    bs = BeautifulSoup(html,'lxml')
  22.  
    section = bs.find('section',class_='list')
  23.  
    section_list = section.find_all('div',class_='property')
  24.  
    print(len(section_list))
  25.  
    for item in section_list:
  26.  
    # print(item,'\n')
  27.  
    title = item.find('div',class_="property-content-title").text
  28.  
    print(title)
  29.  
    house_info = item.find('div',class_='property-content-info').text
  30.  
    print(house_info)
  31.  
    # position_info = item.find('div',class_='positioninfo').text
  32.  
    # deal_date = item.find('div',class_='dealdate').text
  33.  
    # number = item.find('span',class_='number').text '万'
  34.  
    # unit_price = item.find('div',class_='unitprice').text
  35.  
    # deal_housetxt = item.find('span',class_='dealhousetxt')
  36.  
    # if deal_housetxt != None:
  37.  
    # deal_housetxt = deal_housetxt.text
  38.  
    # else:
  39.  
    # deal_housetxt =''
  40.  
    # span = item.find('span',class_='dealcycletxt')
  41.  
    # span_list = span.find_all('span')
  42.  
    # agent_name = item.find('a',class_='agent_name').text
  43.  
    #
  44.  
    # lst.append((title,house_info,position_info,deal_date,number,unit_price,deal_housetxt,span_list[0].text,span_list[1].text,agent_name))
  45.  
    # print(lst)
  46.  
    # self.save(self,lst)
  47.  
     
  48.  
    def save(self,lst):
  49.  
    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)'
  50.  
    self.mycursor.executemany(sql,lst)
  51.  
    self.mydb.commit()
  52.  
     
  53.  
    def start(self):
  54.  
    for i in range(1,2):
  55.  
    full_url = self.url.format(i)
  56.  
    resp = self.send_request(full_url)
  57.  
    # print(resp.text)
  58.  
    self.parse_html(resp)
  59.  
     
  60.  
    pass
  61.  
     
  62.  
    if __name__ == '__main__':
  63.  
    lianjia = Lianjiaspider()
  64.  
    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

  1.  
    import pymongo
  2.  
     
  3.  
    # 连接到服务器
  4.  
    client = pymongo.MongoClient('localhost',27017)
  5.  
     
  6.  
    # 获取要操作的数据库
  7.  
    # db = client.school
  8.  
    db = client['school']
  9.  
    # print(db)
  10.  
     
  11.  
    # 获取要操作的集合
  12.  
    # collection = db.student
  13.  
    collection = db['student']
  14.  
    # print(collection)
  15.  
     
  16.  
    # 执行插入操作
  17.  
    # stu = {'name':'张一个一个地','age':20,'gender':'女'}
  18.  
    # collection.insert_one(stu)
  19.  
     
  20.  
    # 一次插入多条数据
  21.  
    lst = [
  22.  
    {'name':'王二二','age':23},
  23.  
    {'name':'张三三','age':26},
  24.  
    {'name':'李思思','gender':'女'}
  25.  
    ]
  26.  
    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)

  1.  
    import requests
  2.  
    from bs4 import BeautifulSoup
  3.  
    import pymongo
  4.  
     
  5.  
    class Lianjiaspider():
  6.  
     
  7.  
    def __init__(self):
  8.  
    self.url = 'https://chongqing.anjuke.com/sale/jiangbei/p{0}/?from=HomePage_TopBar'
  9.  
    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'}
  10.  
     
  11.  
    def send_request(self,url):
  12.  
    resp = requests.get(url,headers=self.headers)
  13.  
    if resp.status_code == 200:
  14.  
    return resp
  15.  
     
  16.  
    def parse_html(self,resp):
  17.  
    lst = []
  18.  
    html = resp.text
  19.  
    bs = BeautifulSoup(html,'lxml')
  20.  
    section = bs.find('section',class_='list')
  21.  
    section_list = section.find_all('h3')
  22.  
    print(section_list)
  23.  
    print(len(section_list))
  24.  
    for item in section_list:
  25.  
    print(item,'\n')
  26.  
    total = item.find('p', class_='property-price-total')
  27.  
    print(total)
  28.  
     
  29.  
    # title = item.find('div',class_="property-content-title").text
  30.  
    # print(title)
  31.  
     
  32.  
    title = item.find('div', class_="property-content-title").text
  33.  
    house_info = item.find('div',class_='houseinfo').text
  34.  
    position_info = item.find('div',class_='positioninfo').text
  35.  
    deal_date = item.find('div',class_='dealdate').text
  36.  
    number = item.find('span',class_='number').text '万'
  37.  
    unit_price = item.find('div',class_='unitprice').text
  38.  
    deal_housetxt = item.find('span',class_='dealhousetxt')
  39.  
    if deal_housetxt != None:
  40.  
    deal_housetxt = deal_housetxt.text
  41.  
    else:
  42.  
    deal_housetxt =''
  43.  
    span = item.find('span',class_='dealcycletxt')
  44.  
    span_list = span.find_all('span')
  45.  
    agent_name = item.find('a',class_='agent_name').text
  46.  
     
  47.  
    lst.append({'title':title,
  48.  
    'house_info':house_info,
  49.  
    'position_info':position_info,
  50.  
    'deal_data':deal_date,
  51.  
    'total_price':number,
  52.  
    'unit_price':unit_price,
  53.  
    'deal_house_txt':deal_housetxt,
  54.  
    'deal_money':span_list[0].text,
  55.  
    'deal_date':span_list[1].text,
  56.  
    'agent_name':agent_name})
  57.  
     
  58.  
    # print(lst)
  59.  
    self.save(self,lst)
  60.  
     
  61.  
    def save(self,lst):
  62.  
    # 获取连接对象
  63.  
    client = pymongo.MongoClient('localhost',27017)
  64.  
     
  65.  
    # 获取要操作的数据库
  66.  
    db = client['lianjia']
  67.  
     
  68.  
    # 获取collection
  69.  
    collection = db['collection_lianjia']
  70.  
    collection.insert_many(lst)
  71.  
     
  72.  
    def start(self):
  73.  
    for i in range(1,2):
  74.  
    full_url = self.url.format(i)
  75.  
    resp = self.send_request(full_url)
  76.  
    # print(resp.text)
  77.  
    self.parse_html(resp)
  78.  
     
  79.  
    pass
  80.  
     
  81.  
    if __name__ == '__main__':
  82.  
    lianjia = Lianjiaspider()
  83.  
    lianjia.start()
学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgkehah
系列文章
更多 icon
同类精品
更多 icon
继续加载