当前位置:Gxlcms > Python > Python爬取51cto数据并存入MySQL方法详解

Python爬取51cto数据并存入MySQL方法详解

时间:2021-07-01 10:21:17 帮助过:98人阅读

【相关学习推荐:python教程】

实验环境

1.安装Python 3.7

2.安装requests, bs4,pymysql 模块

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

可参考https://www.jb51.net/article/194104.htm

2.编写代码

  1. # 51cto 博客页面数据插入mysql数据库
  2. # 导入模块
  3. import re
  4. import bs4
  5. import pymysql
  6. import requests
  7. # 连接数据库账号密码
  8. db = pymysql.connect(host='172.171.13.229',
  9. user='root', passwd='abc123',
  10. db='test', port=3306,
  11. charset='utf8')
  12. # 获取游标
  13. cursor = db.cursor()
  14. def open_url(url):
  15. # 连接模拟网页访问
  16. headers = {
  17. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
  18. 'Chrome/57.0.2987.98 Safari/537.36'}
  19. res = requests.get(url, headers=headers)
  20. return res
  21. # 爬取网页内容
  22. def find_text(res):
  23. soup = bs4.BeautifulSoup(res.text, 'html.parser')
  24. # 博客名
  25. titles = []
  26. targets = soup.find_all("a", class_="tit")
  27. for each in targets:
  28. each = each.text.strip()
  29. if "置顶" in each:
  30. each = each.split(' ')[0]
  31. titles.append(each)
  32. # 阅读量
  33. reads = []
  34. read1 = soup.find_all("p", class_="read fl on")
  35. read2 = soup.find_all("p", class_="read fl")
  36. for each in read1:
  37. reads.append(each.text)
  38. for each in read2:
  39. reads.append(each.text)
  40. # 评论数
  41. comment = []
  42. targets = soup.find_all("p", class_='comment fl')
  43. for each in targets:
  44. comment.append(each.text)
  45. # 收藏
  46. collects = []
  47. targets = soup.find_all("p", class_='collect fl')
  48. for each in targets:
  49. collects.append(each.text)
  50. # 发布时间
  51. dates=[]
  52. targets = soup.find_all("a", class_='time fl')
  53. for each in targets:
  54. each = each.text.split(':')[1]
  55. dates.append(each)
  56. # 插入sql 语句
  57. sql = """insert into blog (blog_title,read_number,comment_number, collect, dates)
  58. values( '%s', '%s', '%s', '%s', '%s');"""
  59. # 替换页面 \xa0
  60. for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):
  61. reads = re.sub('\s', '', reads)
  62. comment = re.sub('\s', '', comment)
  63. collects = re.sub('\s', '', collects)
  64. cursor.execute(sql % (titles, reads, comment, collects,dates))
  65. db.commit()
  66. pass
  67. # 统计总页数
  68. def find_depth(res):
  69. soup = bs4.BeautifulSoup(res.text, 'html.parser')
  70. depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text
  71. return int(depth)
  72. # 主函数
  73. def main():
  74. host = "https://blog.51cto.com/13760351"
  75. res = open_url(host) # 打开首页链接
  76. depth = find_depth(res) # 获取总页数
  77. # 爬取其他页面信息
  78. for i in range(1, depth + 1):
  79. url = host + '/p' + str(i) # 完整链接
  80. res = open_url(url) # 打开其他链接
  81. find_text(res) # 爬取数据
  82. # 关闭游标
  83. cursor.close()
  84. # 关闭数据库连接
  85. db.close()
  86. if __name__ == '__main__':
  87. main()

3..MySQL创建对应的表

  1. CREATE TABLE `blog` (
  2. `row_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `blog_title` varchar(52) DEFAULT NULL COMMENT '博客标题',
  4. `read_number` varchar(26) DEFAULT NULL COMMENT '阅读数量',
  5. `comment_number` varchar(16) DEFAULT NULL COMMENT '评论数量',
  6. `collect` varchar(16) DEFAULT NULL COMMENT '收藏数量',
  7. `dates` varchar(16) DEFAULT NULL COMMENT '发布日期',
  8. PRIMARY KEY (`row_id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

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

改进版:

改进内容:

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

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

1.代码如下:

  1. import re
  2. import bs4
  3. import pymysql
  4. import requests
  5. # 连接数据库
  6. db = pymysql.connect(host='172.171.13.229',
  7. user='root', passwd='abc123',
  8. db='test', port=3306,
  9. charset='utf8')
  10. # 获取游标
  11. cursor = db.cursor()
  12. def open_url(url):
  13. # 连接模拟网页访问
  14. headers = {
  15. 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
  16. 'Chrome/57.0.2987.98 Safari/537.36'}
  17. res = requests.get(url, headers=headers)
  18. return res
  19. # 爬取网页内容
  20. def find_text(res):
  21. soup = bs4.BeautifulSoup(res.text, 'html.parser')
  22. # 博客标题
  23. titles = []
  24. targets = soup.find_all("a", class_="tit")
  25. for each in targets:
  26. each = each.text.strip()
  27. if "置顶" in each:
  28. each = each.split(' ')[0]
  29. titles.append(each)
  30. # 阅读量
  31. reads = []
  32. read1 = soup.find_all("p", class_="read fl on")
  33. read2 = soup.find_all("p", class_="read fl")
  34. for each in read1:
  35. reads.append(each.text)
  36. for each in read2:
  37. reads.append(each.text)
  38. # 评论数
  39. comment = []
  40. targets = soup.find_all("p", class_='comment fl')
  41. for each in targets:
  42. comment.append(each.text)
  43. # 收藏
  44. collects = []
  45. targets = soup.find_all("p", class_='collect fl')
  46. for each in targets:
  47. collects.append(each.text)
  48. # 发布时间
  49. dates=[]
  50. targets = soup.find_all("a", class_='time fl')
  51. for each in targets:
  52. each = each.text.split(':')[1]
  53. dates.append(each)
  54. # 插入sql 语句
  55. sql = """insert into blogs (blog_title,read_number,comment_number, collect, dates)
  56. values( '%s', '%s', '%s', '%s', '%s');"""
  57. # 替换页面 \xa0
  58. for titles, reads, comment, collects, dates in zip(titles, reads, comment, collects, dates):
  59. reads = re.sub('\s', '', reads)
  60. reads=int(re.sub('\D', "", reads)) #匹配数字,转换为整型
  61. comment = re.sub('\s', '', comment)
  62. comment = int(re.sub('\D', "", comment)) #匹配数字,转换为整型
  63. collects = re.sub('\s', '', collects)
  64. collects = int(re.sub('\D', "", collects)) #匹配数字,转换为整型
  65. dates = re.sub('\s', '', dates)
  66. cursor.execute(sql % (titles, reads, comment, collects,dates))
  67. db.commit()
  68. pass
  69. # 统计总页数
  70. def find_depth(res):
  71. soup = bs4.BeautifulSoup(res.text, 'html.parser')
  72. depth = soup.find('li', class_='next').previous_sibling.previous_sibling.text
  73. return int(depth)
  74. # 主函数
  75. def main():
  76. host = "https://blog.51cto.com/13760351"
  77. res = open_url(host) # 打开首页链接
  78. depth = find_depth(res) # 获取总页数
  79. # 爬取其他页面信息
  80. for i in range(1, depth + 1):
  81. url = host + '/p' + str(i) # 完整链接
  82. res = open_url(url) # 打开其他链接
  83. find_text(res) # 爬取数据
  84. # 关闭游标
  85. cursor.close()
  86. # 关闭数据库连接
  87. db.close()
  88. #主程序入口
  89. if __name__ == '__main__':
  90. main()

2.创建对应表

  1. CREATE TABLE `blogs` (
  2. `row_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  3. `blog_title` varchar(52) DEFAULT NULL COMMENT '博客标题',
  4. `read_number` int(26) DEFAULT NULL COMMENT '阅读数量',
  5. `comment_number` int(16) DEFAULT NULL COMMENT '评论数量',
  6. `collect` int(16) DEFAULT NULL COMMENT '收藏数量',
  7. `dates` varchar(16) DEFAULT NULL COMMENT '发布日期',
  8. PRIMARY KEY (`row_id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

3.运行代码,验证

升级版

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

1.改进代码:

  1. #末尾修改为:
  2. if __name__ == '__main__':
  3. main()
  4. print("\n\t\t所有数据已成功存放数据库!!! \n")
  5. 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包,查看效果

检查数据库

相关学习推荐:mysql教程

以上就是Python爬取51cto数据并存入MySQL方法详解的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行