原文

1.笔记

#-*- codeing = utf-8 -*-
#@Time : 2020/7/15 22:49
#@Author : HUGBOY
#@File : hello_sqlite3.py
#@Software: PyCharm
'''---------------|Briefing|------------------
sqlite3
——a new way to save data !
------------------------------------''' import sqlite3 #连接 print("Connect code:")
# conn = sqlite3.connect("sql.database")#创建/打开数据库文件
#
# c = conn.cursor()#获取游标
#
# sql = '''
# create table company
# (id int primary key not null,
# name text not null,
# age int not null,
# address char(58),
# salary real);
# ''' #三个点多行语句
#
# #第一次创建 c.execute(sql)#执行sql语句
#
# conn.commit()#提交保存
#
# print("建表成功!")
#
# conn.close()#关闭数据库

2.实例

效果

原码

#-*- codeing = utf-8 -*-
#@Time : 2020/7/16 12:12
#@Author : HUGBOY
#@File : sp_douban2(sql).py
#@Software: PyCharm
# -*- codeing = utf-8 -*-
# @Time : 2020/7/12 19:11
# @Author : HUGBOY
# @File : sp_douban1(excel).py
# @Software: PyCharm
'''----------------------|简介|------------------
#爬虫
#爬取豆瓣TOP250电影数据
#1.爬取网页
#2.逐一解析数据
#3.保存数据
----------------------------------------------''' from bs4 import BeautifulSoup # 网页解析、获取数据
import re # 正则表达式
import urllib.request, urllib.error # 指定URL、获取网页数据
import random
import xlwt # 存到excel的操作
import sqlite3 # 存到数据库操作
import os
from urllib.request import urlretrieve#保存电影海报图 def main():
baseurl = "https://movie.douban.com/top250/?start="
datalist = getdata(baseurl)
#savepath = ".\\豆瓣电影Top250_data.xls"
#savedata(datalist,savepath)
dbpath = ("豆瓣电影Top250_data.db")
savedata(datalist,dbpath)
# 正则表达式匹配规则 findTitle = re.compile(r'<span class="title">(.*)</span>') # 影片片名
findR = re.compile(r'<span class="inq">(.*)</span>') # 一句话评
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>') # 影片评分
findPeople = re.compile(r'<span>(\d*)人评价</span>') # 影评人数-/d 代表数字
findLink = re.compile(r'<a href="(.*?)">') # 影片链接
findImg = re.compile(r'<img.*src="(.*?)"', re.S) # 影片图片-re.S 允许.中含换行符
findBd = re.compile(r'<p class="">(.*?)</p>', re.S) # 影片简介 def getdata(baseurl):
datalist = []
getimg = 0
for i in range(0, 10): # 调用获取页面信息的函数*10次
url = baseurl + str(i * 25)
html = askURL(url) # 保存获取到的网页原码
# 解析网页
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div', class_="item"):
# print(item) #一部电影的所有信息
data = []
item = str(item)
# 提取影片详细信息 title = re.findall(findTitle, item)
if (len(title) == 2):
ctitle = title[0] # 中文名
data.append(ctitle)
otitle = title[1].replace("/", "") # 外文名-去掉'/'和""
data.append(otitle)
else:
data.append(title[0])
data.append("无外文名")
img = re.findall(findImg, item)[0]
data.append(img)
'''--------------------
爬取图片
--------------------'''
os.makedirs('./movie_img/', exist_ok=True)#创建保存目录
getimg+=1
str_getimg = str(getimg)
#格式 urlretrieve(IMAGE_URL, './img/image1.png')
urlretrieve(img, './movie_img/img'+str_getimg+'.png')
link = re.findall(findLink, item)[0] # re库:正则表达式找指定字符串
data.append(link)
rating = re.findall(findRating, item)[0]
data.append(rating)
people = re.findall(findPeople, item)[0]
data.append(people)
r = re.findall(findR, item)
if len(r) != 0:
r = r[0].replace("。", "")
data.append(r)
else:
data.append("无一句评") bd = re.findall(findBd, item)[0]
bd = re.sub('<br(\s+)?/>(\s+)?', " ", bd) # 替换</br>
bd = re.sub('/', " ", bd) # 替换/
data.append(bd.strip()) # 去掉空格 datalist.append(data) # 把一部电影信息存储 #print(datalist)
return datalist # 得到指定Url网页内容
def askURL(url): head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0"}
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
#print(html) 测试
except Exception as rel:
if hasattr(rel, "code"):
print(rel.code)
if hasattr(rel, "reason"):
print(rel.reason)
return html def savedata(datalist,dbpath):
print("save data in sql ...")
create_db(dbpath)
conn = sqlite3.connect(dbpath)
c = conn.cursor() for data in datalist:
for index in range(len(data)):
if index==4 or index==5:#score rated 类型为numeric
continue
data[index]='"'+data[index]+'"'
sql = '''
insert into movie_T250
(
name,fname,img_link,film_link,score,rated,one_cont,instroduction
)
values(%s)'''%",".join(data)
c.execute(sql)
conn.commit()
c.close()
conn.close() def create_db(dbpath):
sql='''
create table movie_T250
(
id integer primary key autoincrement,
name varchar,
fname varchar,
img_link text,
film_link text,
score numeric,
rated numeric,
one_cont text,
instroduction text
);
'''
conn = sqlite3.connect(dbpath)
c = conn.cursor()
c.execute(sql)
conn.commit()
c.close()
print("create table success !") if __name__ == "__main__":
main()
print("爬取完成,奥利给!")

附: Python爬虫 数据库保存数据的更多相关文章

  1. python查询数据库返回数据

    python查询数据库返回数据主要运用到flask框架,pymysql 和 json‘插件’ #!/usr/bin/python # -*- coding: UTF-8 -*- import pymy ...

  2. python爬虫的页面数据解析和提取/xpath/bs4/jsonpath/正则(1)

    一.数据类型及解析方式 一般来讲对我们而言,需要抓取的是某个网站或者某个应用的内容,提取有用的价值.内容一般分为两部分,非结构化的数据 和 结构化的数据. 非结构化数据:先有数据,再有结构, 结构化数 ...

  3. python爬虫26 | 把数据爬取下来之后就存储到你的MySQL数据库。

    小帅b说过 在这几篇中会着重说说将爬取下来的数据进行存储 上次我们说了一种 csv 的存储方式 这次主要来说说怎么将爬取下来的数据保存到 MySQL 数据库 接下来就是 学习python的正确姿势 真 ...

  4. Python爬虫之三种数据解析方式

    一.引入 二.回顾requests实现数据爬取的流程 指定url 基于requests模块发起请求 获取响应对象中的数据 进行持久化存储 其实,在上述流程中还需要较为重要的一步,就是在持久化存储之前需 ...

  5. python从数据库取数据后写入excel 使用pandas.ExcelWriter设置单元格格式

    用python从数据库中取到数据后,写入excel中做成自动报表,ExcelWrite默认的格式一般来说都比较丑,但workbook提供可以设置自定义格式,简单记录个demo,供初次使用者参考. 一. ...

  6. python爬虫——抖音数据

    最近挺火的抖音短视频,不仅带火了一众主播,连不少做电商的也进驻其中,于是今天我来扒一扒这火的不要不要的抖音数据: 一.抓包工具获取用户ID 对于手机app数据,抓包是最直接也是最常见的手段,常用的抓包 ...

  7. python爬虫系列之数据的存储(二):csv库的使用

    上一篇我们讲了怎么用 json格式保存数据,这一篇我们来看看如何用 csv模块进行数据读写. 一.csv简介 CSV (Comma Separated Values),即逗号分隔值(也称字符分隔值,因 ...

  8. python爬虫:将数据保存到本地

    一.python语句存储 1.with open()语句 with open(name,mode,encoding) as file: file.write() name:包含文件名称的字符串; mo ...

  9. 【原创】python爬虫获取网站数据并存入本地数据库

    #coding=utf-8 import urllib import re import MySQLdb dbnumber = MySQLdb.connect('localhost', 'root', ...

随机推荐

  1. 201871030108-冯永萍 实验二 个人项目— D{0-1}背包问题项目报告

    项目 内容 课程班级博客链接 https://edu.cnblogs.com/campus/xbsf/2018CST 这个作业要求链接 https://www.cnblogs.com/nwnu-dai ...

  2. Kafka和Stream架构的使用

    Kafka的单节点运行 启动服务 Kafka 使用 ZooKeeper 如果你还没有 ZooKeeper 服务器,你需要先启动一个 ZooKeeper 服务器. 您可以通过与 kafka 打包在一起的 ...

  3. 6. Mybatis Parameters

    这个元素说的直白点就是定义参数.注意一个语句中只能有一个参数. 所以参数类型在以后的使用中,可能需要复杂的类型,比如hashmap,一个复杂的对象等.例如: <?xml version=&quo ...

  4. 死磕Spring之AOP篇 - Spring AOP两种代理对象的拦截处理

    该系列文章是本人在学习 Spring 的过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring 源码分析 GitHub 地址 进行阅读. Spring 版本:5.1 ...

  5. Box UVA - 1587

    Ivan works at a factory that produces heavy machinery. He has a simple job - he knocks up wooden box ...

  6. Day11_56_在SortedSet中使用泛型

    在SortedSet中使用泛型 import java.util.SortedSet; import java.util.TreeSet; //主类 public class GenericTest0 ...

  7. UI自动化测试框架:PO模式+数据驱动

    1. PO 设计模式简介 2. 工程结构说明 3. 工程代码实现 page 包 action 包 business_process 包 util 包 conf 包 test_data 目录 log 目 ...

  8. Pandas的loc,iloc与ix的用法及区别

    1.先来谈一谈loc,loc这个方法就是你有啥我就用啥,你没有的我不用,pandas对象的index,columns有什么,pd.loc[index,column],index就是pd.index的其 ...

  9. 11- jmeter主要元件

    元件分类 HTTP请求默认值(请求行,请求头,空行,消息体) HTTP信息头管理器: HTTPcookie管理器(1.更真实的模拟用户行为 ,多个请求的关联.第一个请求没有cookie第二个就带了co ...

  10. 移动端小总结(1)---meta、input和单行多行文字溢出省略号

    一.常用META 1. 添加到主屏后的标题(IOS) 1 <meta name="apple-mobile-web-app-title" content="标题&q ...