实验环境

1.安装python 3.7

2.安装requests, bs4,pymysql 模块

实验步骤1.安装环境及模块

可参考

2.编写代码

# 51cto 博客页面数据插入mysql数据库

# 导入模块

import re

import bs4

import pymysql

import requests

# 连接数据库账号密码

db = pymysql.connect(host='172.171.13.229',

user='root', passwd='abc123',

db='test', port=3306,

charset='utf8')

# 获取游标

cursor = db.cursor()

def open_url(url):

# 连接模拟网页访问

headers = {

'user-agent': 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) '

'chrome/57.0.2987.98 safari/537.36'}

res = requests.get(url, headers=headers)

return res

# 爬取网页内容

def find_text(res):

soup = bs4.beautifulsoup(res.text, 'html.parser')

# 博客名

titles = []

targets = soup.find_all("a", class_="tit")

for each in targets:

each = each.text.strip()

if "置顶" in each:

each = each.split(' ')[0]

titles.append(each)

# 阅读量

reads = []

read1 = soup.find_all("p", class_="read fl on")

read2 = soup.find_all("p", class_="read fl")

for each in read1:

reads.append(each.text)

for each in read2:

reads.append(each.text)

# 评论数

comment = []

targets = soup.find_all("p", class_='comment fl')

for each in targets:

comment.append(each.text)

# 收藏

collects = []

targets = soup.find_all("p", class_='collect fl')

for each in targets:

collects.append(each.text)

# 发布时间

dates=[]

targets = soup.find_all("a", class_='time fl')

for each in targets:

each = each.text.split(':')[1]

dates.append(each)

# 插入sql 语句

sql = """insert into blog (blog_title,read_number,comment_number, collect, dates)

values( '%s', '%s', '%s', '%s', '%s');"""

# 替换页面 \xa0

for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):

reads = re.sub('\s', '', reads)

comment = re.sub('\s', '', comment)

collects = re.sub('\s', '', collects)

cursor.execute(sql % (titles, reads, comment, collects,dates))

db.commit()

pass

# 统计总页数

def find_depth(res):

soup = bs4.beautifulsoup(res.text, 'html.parser')

depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text

return int(depth)

# 主函数

def main():

host = "https://blog.51cto.com/13760351"

res = open_url(host) # 打开首页链接

depth = find_depth(res) # 获取总页数

# 爬取其他页面信息

for i in range(1, depth + 1):

url = host + '/p' + str(i) # 完整链接

res = open_url(url) # 打开其他链接

find_text(res) # 爬取数据

# 关闭游标

cursor.close()

# 关闭数据库连接

db.close()

if __name__ == '__main__':

main()

3..mysql创建对应的表

create table `blog` (

`row_id` int(11) not null auto_increment comment '主键',

`blog_title` varchar(52) default null comment '博客标题',

`read_number` varchar(26) default null comment '阅读数量',

`comment_number` varchar(16) default null comment '评论数量',

`collect` varchar(16) default null comment '收藏数量',

`dates` varchar(16) default null comment '发布日期',

primary key (`row_id`)

) engine=innodb auto_increment=1 default charset=utf8;

4.运行代码,查看效果:

改进版:

改进内容:

1.数据库里面的某些字段只保留数字即可

2.默认爬取的内容都是字符串,存放数据库的某些字段,最好改为整型,方便后面数据库操作

1.代码如下:

import re

import bs4

import pymysql

import requests

# 连接数据库

db = pymysql.connect(host='172.171.13.229',

user='root', passwd='abc123',

db='test', port=3306,

charset='utf8')

# 获取游标

cursor = db.cursor()

def open_url(url):

# 连接模拟网页访问

headers = {

'user-agent': 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) '

'chrome/57.0.2987.98 safari/537.36'}

res = requests.get(url, headers=headers)

return res

# 爬取网页内容

def find_text(res):

soup = bs4.beautifulsoup(res.text, 'html.parser')

# 博客标题

titles = []

targets = soup.find_all("a", class_="tit")

for each in targets:

each = each.text.strip()

if "置顶" in each:

each = each.split(' ')[0]

titles.append(each)

# 阅读量

reads = []

read1 = soup.find_all("p", class_="read fl on")

read2 = soup.find_all("p", class_="read fl")

for each in read1:

reads.append(each.text)

for each in read2:

reads.append(each.text)

# 评论数

comment = []

targets = soup.find_all("p", class_='comment fl')

for each in targets:

comment.append(each.text)

# 收藏

collects = []

targets = soup.find_all("p", class_='collect fl')

for each in targets:

collects.append(each.text)

# 发布时间

dates=[]

targets = soup.find_all("a", class_='time fl')

for each in targets:

each = each.text.split(':')[1]

dates.append(each)

# 插入sql 语句

sql = """insert into blogs (blog_title,read_number,comment_number, collect, dates)

values( '%s', '%s', '%s', '%s', '%s');"""

# 替换页面 \xa0

for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):

reads = re.sub('\s', '', reads)

reads=int(re.sub('\d', "", reads)) #匹配数字,转换为整型

comment = re.sub('\s', '', comment)

comment = int(re.sub('\d', "", comment)) #匹配数字,转换为整型

collects = re.sub('\s', '', collects)

collects = int(re.sub('\d', "", collects)) #匹配数字,转换为整型

dates = re.sub('\s', '', dates)

cursor.execute(sql % (titles, reads, comment, collects,dates))

db.commit()

pass

# 统计总页数

def find_depth(res):

soup = bs4.beautifulsoup(res.text, 'html.parser')

depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text

return int(depth)

# 主函数

def main():

host = "https://blog.51cto.com/13760351"

res = open_url(host) # 打开首页链接

depth = find_depth(res) # 获取总页数

# 爬取其他页面信息

for i in range(1, depth + 1):

url = host + '/p' + str(i) # 完整链接

res = open_url(url) # 打开其他链接

find_text(res) # 爬取数据

# 关闭游标

cursor.close()

# 关闭数据库连接

db.close()

#主程序入口

if __name__ == '__main__':

main()

2.创建对应表

create table `blogs` (

`row_id` int(11) not null auto_increment comment '主键',

`blog_title` varchar(52) default null comment '博客标题',

`read_number` int(26) default null comment '阅读数量',

`comment_number` int(16) default null comment '评论数量',

`collect` int(16) default null comment '收藏数量',

`dates` varchar(16) default null comment '发布日期',

primary key (`row_id`)

) engine=innodb auto_increment=1 default charset=utf8;

3.运行代码,验证

升级版

为了能让小白就可以使用这个程序,可以把这个项目打包成exe格式的文件,让其他人,使用电脑就可以运行代码,这样非常方便!

1.改进代码:

#末尾修改为:

if __name__ == '__main__':

main()

print("\n\t\t所有数据已成功存放数据库!!! \n")

time.sleep(5)

2.安装打包模块pyinstaller(cmd安装)

pip install pyinstaller -i https://pypi.tuna.tsinghua.edu.cn/simple/

3.python代码打包

1.切换到需要打包代码的路径下面

2.在cmd窗口运行 pyinstaller -f test03.py (test03为项目名称)

4.查看exe包

在打包后会出现dist目录,打好包就在这个目录里面

5.运行exe包,查看效果

检查数据库

总结:

1.这一篇博客,是在上一篇的基础上改进的,步骤是先爬取首页的信息,再爬取其他页面信息,最后在改进细节,打包exe文件

2.我们爬取网页数据大多数还是存放到数据库的,所以这种方法很实用。

3.其实在此博客的基础上还是可以改进的,重要的是掌握方法即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

python爬取mysql_Python如何爬取51cto数据并存入MySQL相关推荐

  1. python3爬取数据存入mysql_Python如何爬取51cto数据并存入MySQL

    实验环境 1.安装Python 3.7 2.安装requests, bs4,pymysql 模块 实验步骤1.安装环境及模块 2.编写代码 ? 1 2 3 4 5 6 7 8 9 10 11 12 1 ...

  2. 用python爬取网页数据并存入数据库中源代码_Python爬取51cto数据并存入MySQL方法详解...

    [] 实验环境 1.安装Python 3.7 2.安装requests, bs4,pymysql 模块 实验步骤1.安装环境及模块 可参考https://www.jb51.net/article/19 ...

  3. python爬虫开发数据库设计入门经典_Python3实现的爬虫爬取数据并存入mysql数据库操作示例...

    本文实例讲述了Python3实现的爬虫爬取数据并存入mysql数据库操作.分享给大家供大家参考,具体如下: 爬一个电脑客户端的订单.罗总推荐,抓包工具用的是HttpAnalyzerStdV7,与chr ...

  4. Python3爬取企查查网站的企业年表并存入MySQL

    Python3爬取企查查网站的企业年表并存入MySQL 本篇博客的主要内容:爬取企查查网站的企业年报数据,存到mysql中,为了方便记录,分成两个模块来写: 第一个模块是爬取数据+解析数据,并将数据存 ...

  5. Python爬虫(10)selenium爬虫后数据,存入csv、txt并将存入数据并对数据进行查询

    之前的文章有关于更多操作方式详细解答,本篇基于前面的知识点进行操作,如果不了解可以先看之前的文章 Python爬虫(1)一次性搞定Selenium(新版)8种find_element元素定位方式 Py ...

  6. Python爬虫(9)selenium爬虫后数据,存入mongodb实现增删改查

    之前的文章有关于更多操作方式详细解答,本篇基于前面的知识点进行操作,如果不了解可以先看之前的文章 Python爬虫(1)一次性搞定Selenium(新版)8种find_element元素定位方式 Py ...

  7. mysql scrapy 重复数据_大数据python(scrapy)爬虫爬取招聘网站数据并存入mysql后分析...

    基于Scrapy的爬虫爬取腾讯招聘网站岗位数据视频(见本头条号视频) 根据TIOBE语言排行榜更新的最新程序语言使用排行榜显示,python位居第三,同比增加2.39%,为什么会越来越火,越来越受欢迎 ...

  8. python多进程写入mysql_Python实现 多进程导入CSV数据到 MySQL

    前段时间帮同事处理了一个把 CSV 数据导入到 MySQL 的需求.两个很大的 CSV 文件, 分别有 3GB.2100 万条记录和 7GB.3500 万条记录.对于这个量级的数据,用简单的单进程/单 ...

  9. Python用tushare库获取股票数据批量存入mysql成功

    之前用了很多方法无法批量存入mysql中,现在这个方法可以了 首先你需要安装tushare,现在最新版本是1.2.15 2018/10/15 如果之前没有安装,请用"开始-所有程序-附件-命 ...

最新文章

  1. OpenCV 4.5.2 发布
  2. 一个Web Project引用多个Java Project在Eclipse下的配置--转载
  3. 任务完成:我从CNC2018 GetAJob挑战中学到的东西
  4. 天津理工计算机通信工程学院,2018年天津理工大学计算机与通信工程学院811信号与系统考研仿真模拟五套题...
  5. 【CCCC】L3-023 计算图 (30分),dfs搜索+偏导数计算
  6. POJ1753-Flip Game
  7. Nebula Graph数据库 学习笔记
  8. 数据清洗案例 OpenRefine入门
  9. 解决笔记本显示器屏幕亮度无法调节情况
  10. SSH框架(spring+struts2+hibernate)+Mysql实现的会议管理系统(功能包含会议室管理、会议管理、用户管理、部门管理、设备管理、个人资料编辑等)
  11. 手机连不上wifi,一直显示正在获取ip地址
  12. 软考中级软件设计师易错点整理
  13. python代码画樱花主要特色,手机python代码画樱花
  14. 华为手机计算机怎么语音算术,华为自带的语音识别功能太实用了!这样操作,3秒语音变文字...
  15. 基于IjkMediaPlayer的播放器
  16. Glassfish JAVA容器中间件使用(咋个办呢 zgbn)
  17. imac打开terminal终端器
  18. 驱动文件中只有cat/inf/dll文件,怎么安装
  19. VS2015 kb2919355 解决方法汇总
  20. CentOS7环境ZooKeeper集群的安装

热门文章

  1. java判断输入的格式化_Java的字符串及格式化输入输出
  2. php 上传pdf文件损坏,php – 强制下载PDF文件,损坏文件
  3. 二进制代码查看器Binary Viewer下载教程
  4. Mybatis-Dao层实现(通过代理方式)
  5. java修改配置不重启,java运行时修改应用数据,通过jmx修改应用运行数据
  6. Vue 4.0——整合font-awesome解决方案
  7. BIOS——PE无法识别硬盘问题问题解决方案
  8. JAVA——Scanner读取文件
  9. [USACO1.2]回文平方数 Palindromic Squares
  10. springboot中的过滤器、拦截器、监听器整合使用