Python爬取数据并写入MySQL数据库操作示例

  • 更新时间:2020-03-17 09:59:51
  • 编辑:贺飞文

首先我们来爬取 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中只选取列表中某一纵列的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    发布时间:2019-06-03

  • 在python中利用numpy求解多项式以及多项式拟合的方法

    今天小编就为大家分享一篇在python中利用numpy求解多项式以及多项式拟合的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    发布时间:2019-09-08

  • python机器学习:Scikit-learn使用手册

    python机器学习:Scikit-learn使用手册

    scikit-learn是在Python中进行机器学习简单且高效的工具可用于数据挖掘和数据分析,这里提供Scikit-learn 使用手册,欢迎下载

    大小:36.8 MBScikit-learn电子书

  • Python可以这样学

    Python可以这样学

    《Python可以这样学》对Python内部工作原理进行了一定深度的剖析,案例代码使用Python 3.5.1实现和Python 3.6.0,适当介绍了Python代码优化、系统编程和安全编程的有关知识,满足不同层次读者的需要,适合作为Python程序员的开发指南。

    大小:22 MBPython入门电子书

  • Python测试驱动开发(第2版)

    Python测试驱动开发(第2版)

    这本书从最基础的知识开始,讲解Web开发的整个流程,展示如何使用Python做测试驱动开发,全部使用Python 3,并针对新版Django全面升级,欢迎下载

    大小:12.4 MBPython开发电子书

  • 小白入门宝典:Python快速入门魔力手册

    小白入门宝典:Python快速入门魔力手册

    本教程全新的介绍了Python入门基础,以及各种各样的错误避免,以通俗易懂的语言,讲述Python开发,欢迎下载

    大小:11.8 MBpython入门电子书

  • 11招玩转网络安全:用Python,更安全

    11招玩转网络安全:用Python,更安全

    大小:156.5 MB网络安全电子书

  • Python树莓派编程

    Python树莓派编程

    《Python树莓派编程》 将向你展示如何在你新买的、35美元的计算机上通过编程实现一个网络机器人、气象站或是媒体服务器等功能。你将会通过一些简单的实例和有趣的项目学到如何在树莓派

    大小:39.9 MBPython编程电子书

  • Python机器学习(第2版)

    Python机器学习(第2版)

    《Python机器学习》是一本关于Python的电子书资源,涉及Python、机器学习等相关内容,本文提供大小为198MB的超清第2PDF格式电子书下载,希望大家能够喜欢。

    大小:59.6 MBPython电子书

  • Python神经网络编程

    Python神经网络编程

    这是一本自己动手用Python编写神经网络的力作,详细介绍了理解神经网络如何工作所必须的基础知识,并介绍了所需的微积分知识和树莓派知识,欢迎下载

    大小:11.5 MBPython编程电子书

  • Python数据分析与挖掘实战

    Python数据分析与挖掘实战

    10余名大数据挖掘行业杰出权威专家和科技人员,10多年大数据分析资询与执行工作经验结晶体。从大数据挖掘的运用来看,以电力工程、航空公司、诊疗、互联网技术、生产加工及其公共文化

    大小:46.8 MBPython电子书

用户留言