如何保存到数据库
import requests
import bs4
import urllib.request
import random
import time
import csv
import pymysql
def getRequest(url):
"""
获取数据
:param url: 请求网址
:return:返回请求的页面内容
"""
# url = 'https://book.douban.com/subject/1255625/comments/'
# 请求头,模拟浏览器
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36 Core/1.77.119.400 QQBrowser/10.9.4817.400'}
req = urllib.request.Request(url=url,headers=headers)
# r.status_code
return req
def getData(url,commentAll):
'''
解析数据
'''
req = getRequest(url)
html = urllib.request.urlopen(req)
data = html.read()
soup = bs4.BeautifulSoup(data,'html.parser')
div = soup.find('div',id='comments')
for li in div.find_all('li',{'class':'comment-item'}):
info = li.find('span',{'class':'comment-info'})
# 评论人
username = info.find('a').string
#评论时间
comment_time = info.find('a',{'class':'comment-time'}).string
# 评论内容
comment = li.find('span',{'class':'short'}).string
# 装入字典
talk = {'评论人':username,'评论时间':comment_time,'评论内容':comment}
commentAll.append(talk)
def writeInto(commentAll):
'''
保存数据到表格中
'''
with open('experiment.csv','w',encoding='utf8') as file:
# 向表格中写入数据
writer = csv.writer(file)
# 数据在commentAll列表中,循环遍历列表,读取数据
for i in commentAll:
# 读取字段
info = [i['评论人'],i['评论时间'],i['评论内容']]
# 写入文本文件
writer.writerow(info)
# 关闭
file.close()
# 函数,直接输入main
if __name__ == '__main__':
# 初始化
commentAll = []
# 爬取三页,0、1、2
for i in range(0,3):
# 网页地址
url = 'https://book.douban.com/subject/1255625/comments/?limit=20&status=P&sort=new_score&status=P'
# 调用函数
getData(url,commentAll)
# 每爬取一个页面数据,休息10秒,防止被封号
time.sleep(10)
# 调用函数
writeInto(commentAll)
你这问题问的大而空
你要先确定到底是个什么数据库,是mysql、sqlserver、oracle、access还是pg
然后安装对应的类库
剩下的无非就是connect,拼接个insert语句,执行