Python的学习总结

将爬取的数据存入的MySQL数据库

  1. 1.python调用的MySQL数据库通常通过MySQLdb的模块

    命令行安装:

    pip install python-mysq
    
  2. 连接数据库:

		#!/usr/bin/python 
		# -*- coding: UTF-8 -*-  
		import MySQLdb  
		# 连接数据库      连接地址  账号  密码   数据库   数据库编码  
		db = MySQLdb.connect("localhost", "root", "123456", "test" , charset="utf8") 
		  
		# 使用cursor()方法获取操作游标 
		cursor = db.cursor() 
		  
		# 使用execute方法执行SQL语句 
		cursor.execute("SELECT VERSION()") 
		  
		# 使用 fetchone() 方法获取一条数据库。 
		data = cursor.fetchone() 
		  
		print "Database version : %s " % data 
		  
		# 关闭数据库连接 
		db.close()
  1. 代码:
		import requests
		from bs4 import BeautifulSoup
		import re
		import MySQLdb
		
		#连接数据库
		db = MySQLdb.connect("localhost","root","123456","test",charset="utf8")
		cursor = db.cursor()
		#数据库中如果已经有wini此表,则删除已存在的此表
		cursor.execute("DROP TABLE IF EXISTS wini")
		#创建新表wini
		sql = r"""CREATE TABLE wini(
		       id INT(100)NOT NULL,

       		   name CHAR(100)NOT NULL,

      		   iperf CHAR(100)NOT NULL,

      		   type CHAR(100)NOT NULL,)"""
		cursor.execute(sql)
		
		url = 'http://www.*****.com/index.php/Home/Index/index.html'
		html = requests.get(url)
		soup = BeautifulSoup(html.content,'html.parser')
		#找到所有class为wi_td的td元素
		tag_a= soup.find_all(name="td", attrs={"class":re.compile(r"wi_td")})
		#检查索引,以便于后面爬取工作
		#for n,i in enumerate(tag_a):
		#    print(n,i.text)
		demo_list = []
		for i in tag_a[4:128]:
		    demo_list.append(i.text)
		while demo_list:
		    print(int(demo_list[0:4][0]),demo_list[0:4][1],int(float(demo_list[0:4][2])*10000),int(float(demo_list[0:4][3])*10000))
		#   测试数据类型
		#   print(type(demo_list[0:4][0]), type(demo_list[0:4][1]), type(demo_list[0:4][2]), type(demo_list[0:4][3]))
		    insert_message = ("INSERT INTO wini(id,name,iperf,type)" "VALUES(%s,%s,%s,%s)")
		    data = (int(demo_list[0:4][0]),demo_list[0:4][1],int(float(demo_list[0:4][2])*10000),int(float(demo_list[0:4][3])*10000))
		#   数据插入数据库
		    cursor.execute(insert_message, data)
		    db.commit()
		    del demo_list[0:4]
		#关闭数据库
		db.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值