python写入MySQL数据库

这次给大家带来的是将python爬取的数据写入数据库
将爬取得数据写入数据库的步骤:

  • 连接数据库;
  • 创建表
  • 将数据写入数据库;
  • 关闭数据库。

1.连接数据库
在连接自己的数据库之前我们应先导入import MySQLdb模块

  • host:自己的主机号,一般写127.0.0.1就可以了
  • port:端口号
  • user:root
  • passwd:密码
  • db:连接的数据库名称
  • charset:编码
import MySQLdb
conn = MySQLdb.Connect(host = '127.0.0.1',
                       port = 3306,
                       user = 'root',
                       passwd = '*******',
                       db = '******',
                       charset='utf8')

2.创建表

  • cursor(): 使用该链接创建并返回的游标
  • execute():执行一个数据库查询和命令
  • commit():提交但前事物(写入数据时也会用到)
cur = conn.cursor()
sql = """CREATE TABLE xiaoshuo(
                 title  CHAR(20),
                 sec_title  CHAR(20),
                 content  VARCHAR(6499))"""
cur.execute(sql)
conn.commit()

3.写入数据库
这里有两种方法写入:
第一种:

into = "INSERT INTO scrapy_yilong2(title,author,comment,`time`) VALUES (%s,%s, %s, %s)"
values = (item['title'],item['author'],item['comment'],item['time'])
cur.execute(into, values)
conn.commit()

第二种:

cur.execute("INSERT INTO scrapy_yilong2(title,author,comment,`time`)  VALUES  (%s,%s, %s, %s);%(item['title'],item['author'],item['comment'],item['time']))
conn.commit()

但是建议大家使用第一种,第一种比较规范
还有就是,传入数据后记得提交,也就是commit()函数要记得写

4.关闭数据库

conn.close()

在这里,给大家一个完整的实例,以供大家体会,下面这个例子是爬取多本小说,并写入数据库
如果大家想更加的了解这个代码,可以查看我的上一篇博客上一篇:爬取多本小说并写入多个txt文档

# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
import requests
import re
import MySQLdb
#解决出现的写入错误
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

#可以获取多本文章
MAX_RETRIES = 20
url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi'
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=MAX_RETRIES)
session.mount('https://', adapter)
session.mount('http://', adapter)
r = session.get(url)

print('连接到mysql服务器...')
conn = MySQLdb.connect(host='127.0.0.1', user='root', passwd='123mysql', db='onefive',charset='utf8')
print('连接上了!')
cur = conn.cursor()
#判断表是否存在,若存在则删除此表
cur.execute("DROP TABLE IF EXISTS AGENT")
#创建表
sql = """CREATE TABLE xiaoshuo(
                 title  CHAR(20),
                 sec_title  CHAR(20),
                 content  VARCHAR(6499))"""
cur.execute(sql)
conn.commit()

#爬取首页各小说链接,并写入列表
url1 = 'http://www.biquge.com.tw/'
html = requests.get(url1).content
soup = BeautifulSoup(html,'html.parser')
article = soup.find(id="main")
texts = []
for novel in article.find_all(href=re.compile('http://www.biquge.com.tw/')):
    #小说链接
    nt = novel.get('href')
    texts.append(nt)
    #print nt     #可供检验
    new_text = []
    for text in texts:
        if text not in new_text:
            new_text.append(text)
#将刚刚的列表写入一个新列表,以供遍历,获取各个链接
h = []
h.append(new_text)
l = 0
for n in h:
    while l<=len(n)-1:
        #爬取小说的相关信息及目录和目录链接
        url2 = n[l]
        html = requests.get(url2).content
        soup = BeautifulSoup(html, 'html.parser')
        a = []
        #爬取相关信息及目录
        for catalogue in soup.find_all(id="list"):
            timu = soup.find(id="maininfo")
            name1 = timu.find('h1').get_text()
            tm = timu.get_text()
            e_cat = catalogue.get_text('\n')
            print name1
            # print tm
            # print e_cat
            end1 = u'%s%s%s%s' % (tm, '\n', e_cat, '\n')
            cur.execute("INSERT INTO xiaoshuo(title) VALUES ('%s');" % (name1))
            conn.commit()
        #爬取各章链接
        for link in catalogue.find_all(href=re.compile(".html")):
           lianjie = 'http://www.biquge.com.tw/' + link.get('href')
           a.append(lianjie)
        #将各章的链接列表写入一个新列表,以供遍历,获取各章的列表
        k = []
        k.append(a)
        j = 0
        for i in k:
           while j <= len(i) - 1:
                #爬取各章小说内容
                url = 'http://www.biquge.com.tw/14_14055/9194140.html'
                finallyurl = i[j]
                html = requests.get(finallyurl).content
                soup = BeautifulSoup(html, 'html.parser')
                tit = soup.find('div', attrs={'class': 'bookname'})
                title = tit.h1
                content = soup.find(id='content').get_text()
                section = title.get_text()
                print section
                print content
                j += 1
                #end2 = u'%s%s%s%s' % (title , '\n' , content , '\n')
                cur.execute("INSERT INTO xiaoshuo(sec_title,content) VALUES ('%s', '%s');" % (section, content))
                conn.commit()
                          
        l+=1
conn.close()

猜你喜欢

转载自blog.csdn.net/m0_43445668/article/details/84111157