将爬取的数据存入的MySQL数据库
-
1.python调用的MySQL数据库通常通过MySQLdb的模块
命令行安装:
pip install python-mysq
-
连接数据库:
#!/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()
- 代码:
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()