Python爬取数据并写入爬取数据并写入MySQL数据库的实例数据库的实例
今天小编就为大家分享一篇Python爬取数据并写入MySQL数据库的实例,具有很好的参考价值,希望对大家有
所帮助。一起跟随小编过来看看吧
首先我们来爬取 http://html-color-codes.info/color-names/ 的一些数据。
按 F12 或 ctrl+u 审查元素,结果如下:
结构很清晰简单,我们就是要爬 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] # 获取的列表
评论0