Python爬取数据并写入MySQL数据库的实例


Posted in Python onJune 21, 2018

首先我们来爬取 http://html-color-codes.info/color-names/ 的一些数据。

Python爬取数据并写入MySQL数据库的实例

按 F12 或 ctrl+u 审查元素,结果如下:

Python爬取数据并写入MySQL数据库的实例

结构很清晰简单,我们就是要爬 tr 标签里面的 style 和 tr 下几个并列的 td 标签,下面是爬取的代码:

#!/usr/bin/env python
# coding=utf-8
import requests
from bs4 import BeautifulSoup
import MySQLdb
print('连接到mysql服务器...')
db = MySQLdb.connect("localhost","hp","Hp12345.","TESTDB")
print('连接上了!')
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS COLOR")
sql = """CREATE TABLE COLOR (
  Color CHAR(20) NOT NULL,
  Value CHAR(10),
  Style CHAR(50) )"""
cursor.execute(sql)
hdrs = {'User-Agent':'Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)'}
url = "http://html-color-codes.info/color-names/"
r = requests.get(url, headers = hdrs)
soup = BeautifulSoup(r.content.decode('gbk', 'ignore'), 'lxml')
trs = soup.find_all('tr') # 获取全部tr标签成为一个列表
for tr in trs:    # 遍历列表里所有的tr标签单项
 style = tr.get('style') # 获取每个tr标签里的属性style
 tds = tr.find_all('td') # 将每个tr标签下的td标签获取为列表
 td = [x for x in tds] # 获取的列表
 name = td[1].text.strip()  # 直接从列表里取值
 hex = td[2].text.strip()
 # print u'颜色: ' + name + u'颜色值: '+ hex + u'背景色样式: ' + style
 # print 'color: ' + name + '\tvalue: '+ hex + '\tstyle: ' + style
 insert_color = ("INSERT INTO COLOR(Color,Value,Style)" "VALUES(%s,%s,%s)")
 data_color = (name, hex, style)
 cursor.execute(insert_color, data_color)
 db.commit()
 # print '******完成此条插入!' 
print '爬取数据并插入mysql数据库完成...'

运行结果:

Python爬取数据并写入MySQL数据库的实例

$ mysql -u hp -p
Enter password: 
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 28
Server version: 5.7.17 MySQL Community Server (GPL)
Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use TESTDB
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from COLOR;
+----------------------+--------+----------------------------------------+
| Color    | Value | Style         |
+----------------------+--------+----------------------------------------+
| IndianRed   | CD5C5C | background-color:indianred;   |
| LightCoral   | F08080 | background-color:lightcoral;   |
| Salmon    | FA8072 | background-color:salmon;    |
| DarkSalmon   | E9967A | background-color:darksalmon;   |
| LightSalmon   | FFA07A | background-color:lightsalmon;   |
| Crimson    | DC143C | background-color:crimson;    |
| Red     | FF0000 | background-color:red;     |
| FireBrick   | B22222 | background-color:fireBrick;   |
| DarkRed    | 8B0000 | background-color:darkred;    |
| Pink     | FFC0CB | background-color:pink;     |
| LightPink   | FFB6C1 | background-color:lightpink;   |
| HotPink    | FF69B4 | background-color:hotpink;    |
| DeepPink    | FF1493 | background-color:deeppink;    |
...
| AntiqueWhite   | FAEBD7 | background-color:antiquewhite;   |
| Linen    | FAF0E6 | background-color:linen;    |
| LavenderBlush  | FFF0F5 | background-color:lavenderblush;  |
| MistyRose   | FFE4E1 | background-color:mistyrose;   |
| Gainsboro   | DCDCDC | background-color:gainsboro;   |
| LightGrey   | D3D3D3 | background-color:lightgrey;   |
| Silver    | C0C0C0 | background-color:silver;    |
| DarkGray    | A9A9A9 | background-color:darkgray;    |
| Gray     | 808080 | background-color:gray;     |
| DimGray    | 696969 | background-color:dimgray;    |
| LightSlateGray  | 778899 | background-color:lightslategray;  |
| SlateGray   | 708090 | background-color:slategray;   |
| DarkSlateGray  | 2F4F4F | background-color:darkslategray;  |
| Black    | 000000 | background-color:black;    |
+----------------------+--------+----------------------------------------+
143 rows in set (0.00 sec)

以上这篇Python爬取数据并写入MySQL数据库的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python help()函数用法详解
Mar 11 Python
Python的Flask开发框架简单上手笔记
Nov 16 Python
学习python之编写简单乘法口诀表实现代码
Feb 27 Python
轻松实现TensorFlow微信跳一跳的AI
Jan 05 Python
python使用jieba实现中文分词去停用词方法示例
Mar 11 Python
python实现list由于numpy array的转换
Apr 04 Python
PyQtGraph在pyqt中的应用及安装过程
Aug 04 Python
python脚本调用iftop 统计业务应用流量的思路详解
Oct 11 Python
用什么库写 Python 命令行程序(示例代码详解)
Feb 20 Python
Elasticsearch py客户端库安装及使用方法解析
Sep 14 Python
用Python爬虫破解滑动验证码的案例解析
May 06 Python
Python实现byte转integer
Jun 03 Python
python实现黑客字幕雨效果
Jun 21 #Python
python实现内存监控系统
Mar 07 #Python
Python之csv文件从MySQL数据库导入导出的方法
Jun 21 #Python
python 从csv读数据到mysql的实例
Jun 21 #Python
OPENCV去除小连通区域,去除孔洞的实例讲解
Jun 21 #Python
python读取文本绘制动态速度曲线
Jun 21 #Python
python实现可视化动态CPU性能监控
Jun 21 #Python
You might like
PHP 存储文本换行实现方法
2010/01/05 PHP
PHP中读取文件的8种方法和代码实例
2014/08/05 PHP
php微信开发之关键词回复功能
2018/06/13 PHP
jQuery如何取id有.的值一般的方法是取不到的
2014/04/18 Javascript
JQuery中DOM事件合成用法实例分析
2015/06/13 Javascript
jquery调整表格行tr上下顺序实例讲解
2016/01/09 Javascript
Bootstrap栅格系统学习笔记
2016/11/25 Javascript
JavaScript之排序函数_动力节点Java学院整理
2017/06/30 Javascript
javascript中的event loop事件循环详解
2018/12/14 Javascript
Vue将页面导出为图片或者PDF
2020/08/17 Javascript
Vue动态生成表格的行和列
2019/07/18 Javascript
详解将微信小程序接口Promise化并使用async函数
2019/08/05 Javascript
VUE页面中通过双击实现复制表格中内容的示例代码
2020/06/11 Javascript
Python中用于检查英文字母大写的isupper()方法
2015/05/19 Python
Django学习笔记之Class-Based-View
2017/02/15 Python
Python3中的列表,元组,字典,字符串相关知识小结
2017/11/10 Python
使用Python的turtle模块画图的方法
2017/11/15 Python
Python操作MongoDB数据库的方法示例
2018/01/04 Python
Python实现matplotlib显示中文的方法详解
2018/02/06 Python
详解python分布式进程
2018/10/08 Python
python过滤中英文标点符号的实例代码
2019/07/15 Python
Python实现鼠标自动在屏幕上随机移动功能
2020/03/14 Python
Python 无限级分类树状结构生成算法的实现
2021/01/21 Python
python中numpy数组与list相互转换实例方法
2021/01/29 Python
Html5游戏开发之乒乓Ping Pong游戏示例(二)
2013/01/21 HTML / CSS
HTML5 Canvas中使用用路径描画圆弧
2015/01/01 HTML / CSS
将n个数按输入顺序的逆序排列,用函数实现
2012/11/14 面试题
工程师求职简历的自我评价分享
2013/10/10 职场文书
计算机专业学生的自我评价
2013/12/15 职场文书
财务管理职业生涯规划书
2014/02/26 职场文书
政府法律服务方案
2014/06/14 职场文书
安全生产一岗双责责任书
2014/07/28 职场文书
2016元旦晚会主持词
2015/07/01 职场文书
SpringRetry重试框架的具体使用
2021/07/25 Java/Android
Redis中有序集合的内部实现方式的详细介绍
2022/03/16 Redis
Android开发手册自定义Switch开关按钮控件
2022/06/10 Java/Android