參考: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等
MySQLWorkbench可視化客戶端

quit 退出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. 查詢數據

