0


爬虫实战(一)Python+selenium自动化获取数据存储到Mysql中

  行话说得好,“爬虫学得好,牢饭吃到饱!”哈哈博主是因这句话入的坑,不为别的就为邀大家一起铁窗泪(bushi),本人虽小牛一只,但是喜爱捣鼓技术,有兴趣的小伙伴们可以共同探讨,也欢迎各位大佬们的指点,愿共同进步!

从Selenium自动化测试到Mysql数据库

  这次计划是翻墙爬取外网某网站https://metrics.torproject.org/rs.html#details/0E300A0942899B995AE08CEF58062BCFEB51EEDF页面的内容,页面中除了正常的文本数据外,还包含了数张js加载的历史数据统计图,将爬取的文本数据直接以字符形式插入表中,图片数据需要处理为二进制后存入。素材使用的工具是**Pycharm**+**python3.7**(个人相当推荐Pycharm,不用考虑python版本于库版本是否匹配的问题,设置黑色的界面风格很有让人写代码的冲动,而且3月4号刚上线chatgpt插件),武器库呢采用的是反爬利器**selenium** web自动化测试,使用版本是3.141.0。从python连接数据库使用的是Pymysql1.0.2。数据库选用的是Mariadb,没找到免费Mysql,民间还是开源的Mariadb呼声更高。
目标

Selenium自动化测试

   selenium的好处在于对于一般网页的反爬虫手段有着很好的反制策略,例如常见的有请求头反爬虫,这个也是最简单的,如果不给定请求头,对方服务器就不会理你,需要设置的参数有User-Agent、Referer和Cookie。还包括有的网站会使用js接口传递数据。甚至有时你会发现自己的请求语句完全正确但是就是定位到页面元素,那就可能是使用了iframe框架,可以理解为网页嵌套。能够做到这些手段的网站不多,对于数据十分金贵的知网算的上一个,这里挖个小坑后面实战项目会有的。对于selenium还不熟悉的小伙伴,博主推荐Selenium with Python中文翻译文档https://selenium-python-zh.readthedocs.io/en/latest/

  1. 库文件
  1. from selenium import webdriver
  2. import pymysql as sql
  3. import time
  4. import random
  1. Webdriver初始化

  webdriver要和自己的chrome浏览器版本相对应(使用火狐浏览器也是可以的),不知道下载哪个版本来这里http://chromedriver.storage.googleapis.com/index.html

  1. self.url="https://metrics.torproject.org/rs.html#details/0E300A0942899B995AE08CEF58062BCFEB51EEDF"
  2. self.driver_path=r"D:\python\chromedriver.exe"#获取数据
  3. self.lable=[]
  4. self.tip=[]
  5. self.content=[]
  6. self.image_f=[]
  7. self.image_s=[]
  8. self.time=[]
  1. 访问页面

  headless赋值为True是开启无头模式测试,初次使用webdriver自动化测试的小伙伴可以去掉这行体验一下

  1. option=webdriver.ChromeOptions()
  2. option.headless=True
  3. option.binary_location=r'D:\Google\Chrome\Application\chrome.exe'
  4. self.driver = webdriver.Chrome(executable_path=self.driver_path,options=option)
  5. self.driver.get(self.url)
  6. time.sleep(10)#这里也可以使用self.driver.implicitly_wait(10)

  implicitly_wait(10) 隐性等待的好处是在设定的时间内只要加载完毕就执行下一步,不用像time.sleep那样强行等待10秒钟

  1. 获取文本数据
  1. # 获取lable
  2. wash=self.driver.find_elements_by_tag_name('h3')
  3. metri.wash_data(wash,0)#wash_data()调用函数对获取到的数据进行清洗#获取tip
  4. wash=self.driver.find_elements_by_class_name('tip')
  5. wash.pop(0)
  6. metri.wash_data(wash,2)#获取content
  7. wash=self.driver.find_elements_by_tag_name('dd')
  8. metri.wash_data(wash,1)

  metri是使用类class的名称:metri=metrics(),由于网页设计的原因有时开发人员的无规律设计可能导致我们获取的数据与期望存在偏差,小问题清洗一下就好了

  1. 获取折线图

  对于这类难获取,获取后难以可视化的情形(如下图),博主非常推荐使用selenium中screenshoot_as_png按元素定位拍照的方法
History折线图

  一筹莫展的时候正好发现了screenshoot的功能,可谓是柳暗花明又一村

  1. self.image_f.append(self.driver.find_element_by_xpath('//*[@id="bw_month"]').screenshot_as_png)
  2. self.image_s.append(self.driver.find_element_by_xpath('//*[@id="weights_month"]').screenshot_as_png)
  3. self.time.append(self.driver.find_element_by_id('history-1m-tab').text)

Mysql数据库

   Mariadb和Oracle甲骨文旗下的Mysql之间的渊源,感兴趣的小伙伴可以去了解一下,Mariadb由于是开源的软件所以更新迭代的次数要比Mysql多,但是两者的语法和大体功能上是相同的

  1. 初始化信息

  在开始运行前一定要安装配置好mysql,我这里使用的是mariadb附上下载链接https://mariadb.com/downloads/,登录界面长这样
Mariadb

  mysql登录信息

  1. def__init__(self):# mysql登录信息
  2. self.host='127.0.0.1'
  3. self.user='root'
  4. self.password='123456'
  5. self.chartset='utf8'#编码格式注意这里不是utf-8,数据库这里的参数配置没有'-'
  6. self.database='metrics_db'#数据库名称
  1. 建立数据库
  1. defset_sqldb(self,sql):
  2. db = sql.connect(
  3. host=self.host,
  4. user=self.user,
  5. password=self.password,
  6. charset=self.chartset,)
  7. cursor=db.cursor()try:
  8. cursor.execute("create database metrics_db character set utf8;")except:pass
  9. cursor.close()
  10. db.close()
  1. 建立数据表
  1. #建立mysql数据表defset_sqlist(self,sql,list_lable):
  2. db=sql.connect(
  3. host=self.host,
  4. user=self.user,
  5. password=self.password,
  6. charset=self.chartset,
  7. database=self.database
  8. )
  9. cursor=db.cursor()
  10. sql="""drop table if exists `%s`"""%((list_lable))
  11. cursor.execute(sql)if list_lable=='History':
  12. sql ="""
  13. create table if not exists `%s`(id int auto_increment primary key comment'序列号',
  14. time VARCHAR(255) not null comment '月份',
  15. graph1 longblob comment '图片',
  16. graph2 longblob comment '图片');"""%(list_lable)else:
  17. sql="""
  18. create table if not exists `%s`(id int auto_increment primary key comment'序列号',
  19. item VARCHAR(255) not null comment '项目名称',
  20. value VARCHAR(255) not null comment '内容',
  21. notes VARCHAR(255) not null comment '备注');"""%(list_lable)
  22. cursor.execute(sql)
  23. cursor.close()
  24. db.close()

  这里博主建表个数是依据爬取页面lable的个数,故在命名时要使用变量建表,格式为代码中sql=“”" “”"三双引号内的部分,这里就不得不吐槽一下python里引号类型是真的多(单引号,双引号,三引号,三双引号)一不留神就用错了

数据库中导入数据

  1. 插入文本数据
  1. # 添加文本数据definsert_txt_sqldb(self,sql,list_lable,st1,st2):
  2. db = sql.connect(
  3. host=self.host,
  4. user=self.user,
  5. password=self.password,
  6. charset=self.chartset,
  7. database=self.database
  8. )
  9. cursor=db.cursor()
  10. sql ="""insert into `%s`(item,value,notes)values ('%s','%s','%s')"""%((list_lable), st1, st2,'null')try:# 执行sql语句
  11. cursor.execute(sql)# 数据库执行sql语句
  12. db.commit()except Exception as res:# 发生错误时回滚
  13. db.rollback()print("error %s"% res)
  14. cursor.close()
  15. db.close()
  1. 插入图片数据
  1. definsert_picture_sqldb(self,sql,list_lable):
  2. db = sql.connect(
  3. host=self.host,
  4. user=self.user,
  5. password=self.password,
  6. charset=self.chartset,
  7. database=self.database
  8. )
  9. cursor=db.cursor()
  10. sql="insert into History(time,graph1,graph2)values(%s,%s,%s);"for i inrange(len(self.time)):try:# 执行sql语句
  11. cursor.execute(sql,[self.time[i],self.image_f[i],self.image_s[i]])# 数据库执行sql语句
  12. db.commit()except Exception as res:# 发生错误时回滚
  13. db.rollback()print("error %s"% res)
  14. cursor.close()
  15. db.close()

  相信细心的小伙伴已经发现了,之前在建表的时候sql语句中分了两种格式,如下,graph1列对应的数据是longblob,blob是二进制数据类型,在数据库中有blob,mediumblob以及longblob,区别就在于存储数据的大小,插入指令为sql=“insert into History(time,graph1,graph2)values(%s,%s,%s);”,cursor.execute(sql,[self.time[i],self.image_f[i],self.image_s[i]])同样表明为变量插入时格式也为变量形式

  1. sql ="""
  2. create table if not exists `%s`(id int auto_increment primary key comment'序列号',
  3. time VARCHAR(255) not null comment '月份',
  4. graph1 longblob comment '图片',
  5. graph2 longblob comment '图片');"""%(list_lable)

结果展示(一)

Configuration标签数据
Configuration标签数据
Properties标签数据
Properties标签数据
History折线图数据
History折线图数据
当然二进制形式不方便查看,我们再从Mysql中将数据提取出保存为本地文件

图片本地存储

  1. defextract_picture(self,sql):
  2. db = sql.connect(
  3. host=self.host,
  4. user=self.user,
  5. password=self.password,
  6. charset=self.chartset,
  7. database=self.database
  8. )
  9. cursor = db.cursor()
  10. cursor.execute('select graph1 from History')
  11. out_1=cursor.fetchall()
  12. cursor.execute('select graph2 from History')
  13. out_2=cursor.fetchall()for i inrange(4):withopen('pair'+str(i+1)+'_graph_1.png',mode="wb")as f1:
  14. f1.write(out_1[i][0])
  15. f1.close()
  16. time.sleep(random.uniform(2,3))withopen('pair'+str(i+1)+'_graph_2.png',mode="wb")as f2:
  17. f2.write(out_2[i][0])
  18. f2.close()
  19. time.sleep(random.uniform(2,3))
  20. cursor.close()
  21. db.close()

结果展示(二)

History折线图片数据本地保存效果

History折线图片数据本地保存

附上代码

感谢大家的驻足,最后附上代码,有什么问题欢迎评论区留言,下期见!

  1. from selenium import webdriver
  2. import pymysql as sql
  3. import time
  4. import random
  5. classmetrics(object):# 初始化信息def__init__(self):# mysql登录信息
  6. self.host='127.0.0.1'
  7. self.user='root'
  8. self.password='123456'
  9. self.chartset='utf8'
  10. self.database='metrics_db'#webdriver初始化
  11. self.url="https://metrics.torproject.org/rs.html#details/0E300A0942899B995AE08CEF58062BCFEB51EEDF"
  12. self.driver_path=r"D:\python\chromedriver.exe"#获取数据
  13. self.lable=[]
  14. self.tip=[]
  15. self.content=[]
  16. self.image_f=[]
  17. self.image_s=[]
  18. self.time=[]#建立数据库defset_sqldb(self,sql):
  19. db = sql.connect(
  20. host=self.host,
  21. user=self.user,
  22. password=self.password,
  23. charset=self.chartset,)
  24. cursor=db.cursor()try:
  25. cursor.execute("create database metrics_db character set utf8;")except:pass
  26. cursor.close()
  27. db.close()#建立mysql数据表defset_sqlist(self,sql,list_lable):
  28. db=sql.connect(
  29. host=self.host,
  30. user=self.user,
  31. password=self.password,
  32. charset=self.chartset,
  33. database=self.database
  34. )
  35. cursor=db.cursor()
  36. sql="""drop table if exists `%s`"""%((list_lable))
  37. cursor.execute(sql)if list_lable=='History':
  38. sql ="""
  39. create table if not exists `%s`(id int auto_increment primary key comment'序列号',
  40. time VARCHAR(255) not null comment '月份',
  41. graph1 longblob comment '图片',
  42. graph2 longblob comment '图片');"""%(list_lable)else:
  43. sql="""
  44. create table if not exists `%s`(id int auto_increment primary key comment'序列号',
  45. item VARCHAR(255) not null comment '项目名称',
  46. value VARCHAR(255) not null comment '内容',
  47. notes VARCHAR(255) not null comment '备注');"""%(list_lable)
  48. cursor.execute(sql)
  49. cursor.close()
  50. db.close()# 数据转换清洗defwash_data(self,wash,flag):if flag==0:for i inrange(len(wash)):
  51. self.lable.append(wash[i].text)
  52. a=0if flag==1:for i inrange(len(wash)):if(wash[i].text)=='':
  53. a+=1if a==2:continue
  54. self.content.append(wash[i].text)
  55. b=0if flag==2:for i inrange(len(wash)):if(b==0):
  56. self.tip.append(wash[i].text)if(b!=0):
  57. b-=1if wash[i].text=='Flags':
  58. b=3if wash[i].text=='Advertised Bandwidth':
  59. b=1# 添加图片数据definsert_picture_sqldb(self,sql,list_lable):
  60. db = sql.connect(
  61. host=self.host,
  62. user=self.user,
  63. password=self.password,
  64. charset=self.chartset,
  65. database=self.database
  66. )
  67. cursor=db.cursor()
  68. sql="insert into History(time,graph1,graph2)values(%s,%s,%s);"for i inrange(len(self.time)):try:# 执行sql语句
  69. cursor.execute(sql,[self.time[i],self.image_f[i],self.image_s[i]])# 数据库执行sql语句
  70. db.commit()except Exception as res:# 发生错误时回滚
  71. db.rollback()print("error %s"% res)
  72. cursor.close()
  73. db.close()#访问网页defwebsite_get(self):
  74. option=webdriver.ChromeOptions()
  75. option.headless=True
  76. option.binary_location=r'D:\Google\Chrome\Application\chrome.exe'
  77. self.driver = webdriver.Chrome(executable_path=self.driver_path,options=option)
  78. self.driver.get(self.url)
  79. time.sleep(10)# 获取lable
  80. wash=self.driver.find_elements_by_tag_name('h3')
  81. metri.wash_data(wash,0)#获取tip
  82. wash=self.driver.find_elements_by_class_name('tip')
  83. wash.pop(0)
  84. metri.wash_data(wash,2)#获取content
  85. wash=self.driver.find_elements_by_tag_name('dd')
  86. metri.wash_data(wash,1)#获取image曲线图
  87. self.image_f.append(self.driver.find_element_by_xpath('//*[@id="bw_month"]').screenshot_as_png)
  88. self.image_s.append(self.driver.find_element_by_xpath('//*[@id="weights_month"]').screenshot_as_png)
  89. self.time.append(self.driver.find_element_by_id('history-1m-tab').text)
  90. self.driver.find_element_by_id('history-6m-tab').click()
  91. self.image_f.append(self.driver.find_element_by_xpath('//*[@id="bw_months"]').screenshot_as_png)
  92. self.image_s.append(self.driver.find_element_by_xpath('//*[@id="weights_months"]').screenshot_as_png)
  93. self.time.append(self.driver.find_element_by_id('history-6m-tab').text)
  94. self.driver.find_element_by_id('history-1y-tab').click()
  95. self.image_f.append(self.driver.find_element_by_xpath('//*[@id="bw_year"]').screenshot_as_png)
  96. self.image_s.append(self.driver.find_element_by_xpath('//*[@id="weights_year"]').screenshot_as_png)
  97. self.time.append(self.driver.find_element_by_id('history-1y-tab').text)
  98. self.driver.find_element_by_id('history-5y-tab').click()
  99. self.image_f.append(self.driver.find_element_by_xpath('//*[@id="bw_years"]').screenshot_as_png)
  100. self.image_s.append(self.driver.find_element_by_xpath('//*[@id="weights_years"]').screenshot_as_png)
  101. self.time.append(self.driver.find_element_by_id('history-5y-tab').text)# 添加文本数据definsert_txt_sqldb(self,sql,list_lable,st1,st2):
  102. db = sql.connect(
  103. host=self.host,
  104. user=self.user,
  105. password=self.password,
  106. charset=self.chartset,
  107. database=self.database
  108. )
  109. cursor=db.cursor()
  110. sql ="""insert into `%s`(item,value,notes)values ('%s','%s','%s')"""%((list_lable), st1, st2,'null')try:# 执行sql语句
  111. cursor.execute(sql)# 数据库执行sql语句
  112. db.commit()except Exception as res:# 发生错误时回滚
  113. db.rollback()print("error %s"% res)
  114. cursor.close()
  115. db.close()# 本地存储图片数据defextract_picture(self,sql):
  116. db = sql.connect(
  117. host=self.host,
  118. user=self.user,
  119. password=self.password,
  120. charset=self.chartset,
  121. database=self.database
  122. )
  123. cursor = db.cursor()
  124. cursor.execute('select graph1 from History')
  125. out_1=cursor.fetchall()
  126. cursor.execute('select graph2 from History')
  127. out_2=cursor.fetchall()for i inrange(4):withopen('pair'+str(i+1)+'_graph_1.png',mode="wb")as f1:
  128. f1.write(out_1[i][0])
  129. f1.close()
  130. time.sleep(random.uniform(2,3))withopen('pair'+str(i+1)+'_graph_2.png',mode="wb")as f2:
  131. f2.write(out_2[i][0])
  132. f2.close()
  133. time.sleep(random.uniform(2,3))
  134. cursor.close()
  135. db.close()# 存入txt文件defsave(self):
  136. db = sql.connect(
  137. host=self.host,
  138. user=self.user,
  139. password=self.password,
  140. charset=self.chartset,
  141. database=self.database
  142. )
  143. cursor = db.cursor()
  144. cursor.execute('select * from Configuration')
  145. out_put = cursor.fetchall()for a in out_put:withopen('metrics_1.txt','a')as f:
  146. f.write(str(a)+'\n')
  147. f.close()
  148. cursor.execute('select * from Properties')
  149. out_put2 = cursor.fetchall()for a in out_put2:withopen('metrics_2.txt','a')as f:
  150. f.write(str(a)+'\n')
  151. f.close()
  152. cursor.close()
  153. db.close()if __name__=="__main__":
  154. metri=metrics()
  155. metri.set_sqldb(sql)
  156. metri.website_get()for i inrange(len(metri.lable)):
  157. metri.set_sqlist(sql,metri.lable[i])# 1for i inrange(11):
  158. metri.insert_txt_sqldb(sql,metri.lable[0],metri.tip[i],metri.content[i])# 2for i inrange(11,len(metri.content)):
  159. metri.insert_txt_sqldb(sql,metri.lable[1],metri.tip[i],metri.content[i])# 3
  160. metri.insert_picture_sqldb(sql,metri.lable[2])#提取sql图片数据并本地保存
  161. metri.extract_picture(sql)#提取所有数据保存到txt文件
  162. metri.save()
标签: 爬虫 selenium mysql

本文转载自: https://blog.csdn.net/angolala/article/details/129368801
版权归原作者 Dancin Puppet 所有, 如有侵权,请联系我们删除。

“爬虫实战(一)Python+selenium自动化获取数据存储到Mysql中”的评论:

还没有评论