Python爬虫(3)——将维基百科词条导入MySQL

最近需要大量爬取数据,像之前那样存储在单个文件中已不合适,本文主要以维基百科为例,将爬取的词条数据导入到MySQL中。

在用Python连接MySQL之前,需要先安装一个Python包pymsql
在Anaconda中的安装过程如下图所示;

这里写图片描述

1.Python连接MySQL数据库

在正式开始之前,先介绍下Python连接MySQL的标准流程。在Python中将数据存储到MySQL的流程主要包括连接数据库创建会话断开数据库连接等。

(1)连接数据库

connection = pymysql.connect(host = 'localhost',
                             user = 'root',
                             password = '123456',
                             db = 'wikiurl',
                             charset = 'utf8mb4')

(2)创建会话

在执行数据存储操作时,该会话会一直存在,在此期间主要执行创建sql语句执行sql语句提交结果等操作。

try:
            #获取会话指针
            with connection.cursor() as cursor:
                #创建sql语句
                sql = "insert into `urls` (`urlname`,`urlhref`) values (%s,%s)" 

                #执行sql语句
                cursor.execute(sql,(url.get_text(),"https://en.wikipedia.org" + url['href']))

                #提交
                connection.commit() 
        finally:
            connection.close()

(3)断开数据库连接

connection.close()

2.将维基百科词条导入MySQL

代码如下所示:

# -*- coding: utf-8 -*-
"""
Created on Thu May  4 21:01:38 2017

@author: zch
"""

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re 
import pymysql.cursors

#请求URL并将结果用UTF-8编码
response = urlopen('https://en.wikipedia.org/wiki/Main_Page').read().decode('utf-8')
#用BeautifulSoup解析
soup = BeautifulSoup(response,'lxml')
#print(soup.head.title.string)
#print(soup)
#p_text = soup.find('a',href=re.compile(r"/wiki/Deaths_in_2017"))
#print(p_text.name,p_text.get_text()) 

#获取所有以/wiki/开头的a标签的href属性
listUrls = soup.find_all('a',href=re.compile('^/wiki/'))
for url in listUrls:
    #过滤掉所有以.jpg或.JPG结尾的url
    if not re.search('\.(jpg|JPG)$',url['href']):
        #输出所有Wikipedia词条和对应的URL链接
        print(url.get_text(),"---->","https://en.wikipedia.org" + url['href'])
        #获取数据库链接
        connection = pymysql.connect(host = 'localhost',
                             user = 'root',
                             password = '123456',
                             db = 'wikiurl',
                             charset = 'utf8mb4')
        try:
            #获取会话指针
            with connection.cursor() as cursor:
                #创建sql语句
                sql = "insert into `urls` (`urlname`,`urlhref`) values (%s,%s)" 

                #执行sql语句
                cursor.execute(sql,(url.get_text(),"https://en.wikipedia.org" + url['href']))

                #提交
                connection.commit() 
        finally:
            connection.close()

执行后MySQL数据库情况如下图所示:

这里写图片描述

如果在运行的过程中,出现以下认证错误的话:

URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>

可以导入ssl模块,并做全局设置:

import ssl
ssl._create_default_https_context = ssl._create_unverified_context
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值