Python爬虫学习笔记5:数据的存储

参考:Python3网络爬虫开发实战

数据存储类型:TXT、 JSON、 csv、MySql、MongoDB、Redis

5.1 文件存储

获取知乎发现页面下面的热门话题
import requests
from pyquery import PyQuery as pq

url = 'https://www.zhihu.com/explore'
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}
html = requests.get(url,headers=headers).text
# print(html.text)
doc = pq(html)
items = doc('.explore-tab .feed-item').items()  # 这里该如何对应页面代码去找节点还是有点蒙
for item in items:
    question = item.find('h2').text()
    author = item.find('.author-link-line').text()
    answer = pq(item.find('.content').html()).text()
    file = open('explore.txt','a',encoding='utf-8')
    file.write('\n'.join([question,author,answer]))
    file.write('\n' + "=" * 50 + '\n')
    file.close()

  

5.1.2 JSON 文件存储 

JSON,全称为 JavaScript O同ect Notation, 也就是 JavaScript对象标记 , 它通过对象和数组的组合 米表示数据,构造简洁但是结构化程度非常高,是一种轻量级的数据交换格式 。

1. 对象和数组 

一切都是对象 。

对象:它在 JavaScript中是使用花括号{}包裹起来的内容,数据结构为{keyl: valuel, key2: value2, ... }的键值对结构。

数组:数组在 JavaScript 中是方括号 []包裹起来的内容,数据结构为[ ”java”, ”javascript”, "vb'’,.. .]的索引结构 。

2. 读取 JSON 

调用 JSON库 的 loads()方法将 JSON 文本字符串转为 JSON对象,可以通过 dumps()方法将 JSON对象转为文本字 符串 

# 读取json
import json

str = '''
[{
    "name":"bob",   # json的数据格式需要使用双引号
    "gender":"male"
},{
    "a":"1",
    "b":"2"
}]  # 由于最外层是中括号,所以最终的数据类型是列表
'''
print(type(str))
data = json.loads(str) #loads转化为json对象
print(data)
print(type(data))
data[0]['name'] # 获取内容
data[0].get('name') # 推荐使用方式,没有不会报错,会返回None,第二个参数可以自定义返回一个默认值


  

3. 输出 JSON 

调用 dumps()方法将 JSON对象转化为字符串 

import json

data = [{
    "1":"1",
    "2":"b"
}]
with open("data.json",'w') as file:
    # dumps 将json对象转化为字符串,
    # indent=2保存为json格式
    # ensure_ascii=False,输出中文
    file.write(json.dumps(data, indent=2, ensure_ascii=False))

  

5.1.3 csv文件存储 

import  csv

with open('data.csv', 'w') as file:
    # delimter 设置分割类型
    # writerows可以写入多行,此时参数就需要为二维列表
    write = csv.writer(file, delimter=' ') # 初始化写入对象
    write.writerow(['id', 'name', 'age'])

# 字典形式
with open("data.csv",'w') as csvfile:
    filenames = ['id','name','age'] # 先定义字段
    write = write.Dictwriter(csvfile, filenames = filenames)
    write.writerheader() # 先写入表头信息,即filenames
    write.writerow('1','2','3')

  

5.2 关系型数据库存储 

关系型数据库有多种,如 SQLite、 MySQL、 Oracle、 SQLServer、 DB2等 

5.2.1 MySQL的存储 

使用的库是 PyMySQL

mac用brew安装mysql,设置初始密码  可以使用mysql -u root -p 进行密码连接

MySQLWorkbench可视化客户端

quit 退出mysql

mysql 查看并修改默认端口号

import pymysql

db = pymysql.connect(host = 'localhost',user='root',password='123456789', port=3306)
# 获取mysql的操作游标
cursor = db.cursor()
# 执行mysql语句
cursor.execute("select version()")
# 获取第一条数据
data = cursor.fetchone()
# 创建spider数据库
cursor.execute("create database spider default character set utf8")
db.close()

  

3. 创建表

# 创建表
import pymysql

db = pymysql.connect(host='localhost', user='root',password='123456789',port=3306,bd='spider')
cursor = db.cursor()
sql='create table if not exists students(id varchar(255) not null,name varchar(255) not null,' \
    'age int not null,primary_key (id))'
cursor.execute(sql)
db.close()

  

4. 插入数据 

import pymysql

id = 'a'
name = 'b'
age = 'c'

db = pymysql.connect(host='localhost', user='root',password='123456789',port='3306',db='spider')
cursor = db.cursor()
sql = 'insert into student(id,name,age) values(%s,%s,%s)'
try:
    cursor.execute(sql,(id,name,age))
    db.commit()
except:
    db.rollback()
db.close()

  

5. 更新数据 

sql =’UPDATE students SET age = %s WHERE name = %s’
try:
    cursor.execute(sql,(25, ’Bob' ))
    db.commit()
except:
    db. rollback ()
    db.close()

  

6. 删除数据 

7. 查询数据 

 

 

posted @ 2019-07-04 15:30  zheng1076  阅读(1475)  评论(0编辑  收藏  举报