Python爬虫的数据入库操作 (python爬虫导入数据库)


Python爬虫是一种自动化技术,主要用于从互联网上抓取数据。在进行Python爬虫时,我们通常需要将爬取到的数据存入数据库中,以便进一步处理和分析。数据入库是Python爬虫的最后一步,也是最为关键的一步。本文将详细介绍,包括数据清洗、数据存储和数据读取等。

一、Python爬虫数据清洗

在进行Python爬虫时,我们通常会面临以下问题:

1. 爬取到的数据格式不规范,需要进行清洗。

2. 爬取的数据量太大,需要筛选出有价值的数据。

3. 爬取到的数据中包含大量垃圾信息,需要进行过滤。

针对这些问题,我们需要进行数据清洗。数据清洗的主要任务是将爬虫爬取的原始数据进行初步的处理和整理,使其能够被后续的数据存储程序正确地处理。具体包括以下几个方面:

1. 字符串处理

在进行数据清洗时,我们通常需要对爬取到的字符串进行处理。比如,我们需要去除字符串中的空格和换行符、将中文转换为Unicode编码等。

2. 数据类型转换

在爬取到的数据存储到数据库中之前,我们需要将其转换为相应的数据类型。比如,将字符串转换为数字、日期等。

3. 数据筛选

爬虫数据中通常包含丰富的信息,但不是所有信息都是有价值的。因此,我们需要对爬取到的数据进行筛选,只选择敲质量较高的数据。

4. 垃圾信息过滤

爬虫爬取的数据中往往包含大量垃圾信息,比如广告信息、网络用语等。这些信息对数据分析和处理都没有任何帮助,因此我们需要将其过滤掉。

二、Python爬虫数据存储

在将Python爬取的数据存储到数据库中时,我们需要确定数据库类型、建立数据库表结构、创建操作数据库的程序等。数据存储的过程包括以下几个步骤:

1. 确定数据库类型

在选择数据库时,应该根据具体的应用场景选择适当的数据库类型。常见的数据库类型包括MySQL、Oracle、SQL Server、MongoDB等。

2. 建立数据库表结构

在将爬取到的数据存储到数据库中之前,我们需要先建立数据库表结构。数据库表结构的设计应该根据需要存储的数据类型进行设计。

3. 创建操作数据库的程序

在将数据存储到数据库中之前,我们需要先编写程序,以便操作数据库。该程序是将Python爬虫爬取到的数据存储到数据库中的关键,需要保证程序的正确性和可靠性。

4. 数据存储

在完成上述准备工作之后,我们就可以将爬取到的数据存储到数据库中了。存储数据库的方式包括以下几种:

(1)使用SQL语句将数据写入数据库中。

(2)使用ORM框架将数据写入数据库中。

(3)使用NoSQL数据库将数据写入数据库中。

三、Python爬虫数据读取

在将Python爬取的数据存储到数据库中之后,我们需要对这些数据进行读取和处理。Python爬虫数据读取的方式包括以下几种:

1. 使用SQL语句进行数据读取,然后使用Python程序进行处理。

2. 使用ORM框架进行数据读取和处理。

3. 直接使用NoSQL数据库进行数据读取和处理。

无论选择哪种方式进行数据读取,都需要保证读取数据的正确性和可靠性,并能够快速地读取到有价值的数据。

本文介绍了,包括数据清洗、数据存储和数据读取等。数据入库是Python爬虫的最后一步,对数据分析和处理具有极为重要的作用。在进行Python爬虫时,我们应该注重数据清洗和存储的工作,并选择适当的数据读取方式进行数据处理。

相关问题拓展阅读:

  • 如何用python爬取豆瓣读书的数据
  • 如何通过python操作xampp里面的MySQL数据库

如何用python爬取豆瓣读书的数据

我们通过bs4解析我们需要的档友字段,如:出版时间,作者/译者,豆瓣评分,售价,评价人数等。

# 解析单个tag页面下单页的信息

def parse_tag_page(html):

try:

soup = BeautifulSoup(html,”lxml”)

tag_name = soup.select(‘title’).get_text().strip()

list_soup = soup.find(‘ul’, {‘class’: ‘subject-list’})

if list_soup == None:

print(‘获取信息列表失败’)

else:

for book_info in list_soup.findAll(‘div’, {‘class’: ‘info’}):

# 书名

title = book_info.find(‘a’).get(‘title’).strip()

# 评价人数

people_num = book_info.find(‘span’, {‘class’: ‘pl’}).get_text().strip()

# 出版信息,作者宽蠢含

pub = book_info.find(‘div’, {‘class’: ‘pub’}).get_text().strip()

pub_list = pub.split(‘/’)

try:

author_info = ‘作者/译者: ‘ + ‘/’.join(pub_list)

except:

author_info = ‘作者/译者: 暂无’

try:

pub_info = ‘出版信息: ‘ + ‘/’慎笑.join(pub_list)

except:

pub_info = ‘出版信息: 暂无’

try:

price_info = ‘价格: ‘ + ‘/’.join(pub_list)

except:

price_info = ‘价格: 暂无’

try:

rating_num= book_info.find(‘span’, {‘class’: ‘rating_nums’}).get_text().strip()

except:

rating_num = ‘0.0’

book_data = {

‘title’: title,

‘people_num’: people_num,

‘author_info’: author_info,

‘pub_info’: pub_info,

‘price_info’: price_info,

‘rating_num’: rating_num

}

# return book_data

if book_data:

save_to_mongo(book_data,tag_name)

except:

print(‘解析错误’)

return None

这两天爬了豆瓣读书的十万条左右的书目信息,用时将近一天,现在趁着这个空闲把代码总结一下,还是菜鸟,都是用的最简单最笨的方法,还请路过的大神不吝赐教。

之一步,先看一下我们需要的库:

import requests#用来请求网页

from bs4 import BeautifulSoup#解析网页

import time#设置延时时间,防止爬取过于频繁被封IP号

import re#正则表达式库

import pymysql#由于爬取的数据太多,我们要把他存入MySQL数据库中,这个库用于连接数据库

import random#这个库里用到了产生随机数的randint函数,和上面的time搭配,使爬取间隔时间随机

这个是豆瓣的网址:x-sorttags-all

我们要从这里获取所有分类的标签链接,进一步去爬取里面的信息,代码先贴上来:

import requests

from bs4 import BeautifulSoup#导入库

url=”httom/tag/?icn=index-nav”

wb_data=requests.get(url)  #请求网址

soup=BeautifulSoup(wb_data.text,”lxml”)  #解析网页信息

tags=soup.select(“#content > div > div.article > div > div > table > tbody > tr > td > a”)

#根据CSS路径查找标签信息,CSS路径获取方法,右键-检查-copy selector,tags返回的是一个列表

for tag in tags:

tag=tag.get_text()    #将列表中的每一个标签信息提取出来

helf=”hom/tag/”

#观察一下豆瓣的网址,基本都是这部分加上标签信息,所以我们要组装网址庆罩,用于爬取标签详情页

url=helf+str(tag)

print(url)    #网址组装完毕,输出

以上我们便爬取了所有标签下的网址,我们将这个文件命名为channel,并在channel中创建一个channel字符串,放上我们所有爬取的网址信息,等下爬取详情页的时候直接从这里提取链接就好了,如下:

channel=”’

tag/程序

”’

现在,我们开始第二个程序。

QQ图片.png

标签页下每一个图片的信息基本都是这样的,我们可以直接从这里提取到标题,作者,出版社,出版时间,价格,评价人数,以及评分等信息迅拍(有些外国作品还会有译者信息),提取方法与提取标签类似,也是根据CSS路径提取。

我们先用一个网址来实验爬取:

url=”htt/tag/科技”

wb_data = requests.get(url)

soup = BeautifulSoup(wb_data.text.encode(“utf-8”), “lxml”)

tag=url.split(“?”).split(“/”)    #从链接里面提取标签信息,方便存储

detils=soup.select(“#subject_list > ul > li > div.info > div.pub”)  #抓取作者,出版社信息,稍后我们用spite()函数再将他们分离出来

scors=soup.select(“#subject_list > ul > li > div.info > div.star.clearfix > span.rating_nums”)   #抓取评分信息

persons=soup.select(“#subject_list > ul > li > div.info > div.star.clearfix > span.pl”)    #评价人数

titles=soup.select(“#subject_list > ul > li > div.info > h2 > a”)   #书名

#以上抓取的都是我们需要的html语言标签信息,我们还需要将他们一一分离出来

for detil,scor,person,title in zip(detils,scors,persons,titles):

#用一个zip()函数实现一亩差羡次遍历

#因为一些标签中有译者信息,一些标签中没有,为避免错误,所以我们要用一个try来把他们分开执行

try:

author=detil.get_text().split(“/”,4).split()     #这是含有译者信息的提取办法,根据“/”  把标签分为五部分,然后依次提取出来

yizhe= detil.get_text().split(“/”, 4)

publish=detil.get_text().split(“/”, 4)

time=detil.get_text().split(“/”, 4).split().split(“-“)   #时间我们只提取了出版年份

price=ceshi_priceone(detil)#因为价格的单位不统一,我们用一个函数把他们换算为“元”

scoe=scor.get_text() if True else “”    #有些书目是没有评分的,为避免错误,我们把没有评分的信息设置为空

person=ceshi_person(person)      #有些书目的评价人数显示少于十人,爬取过程中会出现错误,用一个函数来处理

title=title.get_text().split()  

#当没有译者信息时,会显示IndexError,我们分开处理

except IndexError:

try:

author=detil.get_text().split(“/”, 3).split()

yizhe=””#将detil信息划分为4部分提取,译者信息直接设置为空,其他与上面一样

publish=detil.get_text().split(“/”, 3)

time=detil.get_text().split(“/”, 3).split().split(“-“)

price=ceshi_pricetwo(detil)

scoe=scor.get_text() if True else “”

person=ceshi_person(person)

title=title.get_text().split()

except (IndexError,TypeError):

continue  

#出现其他错误信息,忽略,继续执行(有些书目信息下会没有出版社或者出版年份,但是数量很少,不影响我们大规模爬取,所以直接忽略)

except TypeError:

continue

#提取评价人数的函数,如果评价人数少于十人,按十人处理

def ceshi_person(person):

try:

person = int(person.get_text().split()) – 4>)

except ValueError:

person = int(10)

return person

#分情况提取价格的函数,用正则表达式找到含有特殊字符的信息,并换算为“元”

def ceshi_priceone(price):

price = detil.get_text().split(“/”, 4).split()

if re.match(“USD”, price):

price = float(price) * 6

elif re.match(“CNY”, price):

price = price

elif re.match(“\A$”, price):

price = float(price) * 6

else:

price = price

return price

def ceshi_pricetwo(price):

price = detil.get_text().split(“/”, 3).split()

if re.match(“USD”, price):

price = float(price) * 6

elif re.match(“CNY”, price):

price = price

elif re.match(“\A$”, price):

price = float(price) * 6

else:

price = price

return price

实验成功后,我们就可以爬取数据并导入到数据库中了,以下为全部源码,特殊情况会用注释一一说明。

import requests

from bs4 import BeautifulSoup

import time

import re

import pymysql

from channel import channel   #这是我们之一个程序爬取的链接信息

import random

def ceshi_person(person):

try:

person = int(person.get_text().split()) – 4>)

except ValueError:

person = int(10)

return person

def ceshi_priceone(price):

price = detil.get_text().split(“/”, 4).split()

if re.match(“USD”, price):

price = float(price) * 6

elif re.match(“CNY”, price):

price = price

elif re.match(“\A$”, price):

price = float(price) * 6

else:

price = price

return price

def ceshi_pricetwo(price):

price = detil.get_text().split(“/”, 3).split()

if re.match(“USD”, price):

price = float(price) * 6

elif re.match(“CNY”, price):

price = price

elif re.match(“\A$”, price):

price = float(price) * 6

else:

price = price

return price

#这是上面的那个测试函数,我们把它放在主函数中

def mains(url):

wb_data = requests.get(url)

soup = BeautifulSoup(wb_data.text.encode(“utf-8”), “lxml”)

tag=url.split(“?”).split(“/”)

detils=soup.select(“#subject_list > ul > li > div.info > div.pub”)

scors=soup.select(“#subject_list > ul > li > div.info > div.star.clearfix > span.rating_nums”)

persons=soup.select(“#subject_list > ul > li > div.info > div.star.clearfix > span.pl”)

titles=soup.select(“#subject_list > ul > li > div.info > h2 > a”)

for detil,scor,person,title in zip(detils,scors,persons,titles):

l =  #建一个列表,用于存放数据

try:

author=detil.get_text().split(“/”,4).split()

yizhe= detil.get_text().split(“/”, 4)

publish=detil.get_text().split(“/”, 4)

time=detil.get_text().split(“/”, 4).split().split(“-“)

price=ceshi_priceone(detil)

scoe=scor.get_text() if True else “”

person=ceshi_person(person)

title=title.get_text().split()

except IndexError:

try:

author=detil.get_text().split(“/”, 3).split()

yizhe=””

publish=detil.get_text().split(“/”, 3)

time=detil.get_text().split(“/”, 3).split().split(“-“)

price=ceshi_pricetwo(detil)

scoe=scor.get_text() if True else “”

person=ceshi_person(person)

title=title.get_text().split()

except (IndexError,TypeError):

continue  

except TypeError:

continue

l.append()</p><p><p>#将爬取的数据依次填入列表中</p><p>sql=”INSERT INTO allbooks values(%s,%s,%s,%s,%s,%s,%s,%s,%s)”  #这是一条sql插入语句</p><p>cur.executemany(sql,l)   #执行sql语句,并用executemary()函数批量插入数据库中</p><p>conn.commit()</p><p>#主函数到此结束</p><p># 将Python连接到MySQL中的python数据库中</p><p>conn = pymysql.connect( user=”root”,password=”123123″,database=”python”,charset=’utf8′)</p><p>cur = conn.cursor()</p><p>cur.execute(‘DROP TABLE IF EXISTS allbooks’)   #如果数据库中有allbooks的数据库则删除</p><p>sql = “””CREATE TABLE allbooks(</p><p>title CHAR(255) NOT NULL,</p><p>scor CHAR(255),</p><p>author CHAR(255),</p><p>price CHAR(255),</p><p>time CHAR(255),</p><p>publish CHAR(255),</p><p>person CHAR(255),</p><p>yizhe CHAR(255),</p><p>tag CHAR(255)</p><p>)”””</p><p>cur.execute(sql)  #执行sql语句,新建一个allbooks的数据库</p><p>start = time.clock()   #设置一个时钟,这样我们就能知道我们爬取了多长时间了</p><p>for urls in channel.split():</p><p>urlss=   #从channel中提取url信息,并组装成每一页的链接</p><p><p>for url in urlss:</p><p>mains(url)#执行主函数,开始爬取</p><p>print(url)#输出要爬取的链接,这样我们就能知道爬到哪了,发生错误也好处理</p><p>time.sleep(int(format(random.randint(0,9))))   #设置一个随机数时间,每爬一个网页可以随机的停一段时间,防止IP被封</p><p>end = time.clock()</p><p>print(‘Time Usage:’, end – start)    #爬取结束,输出爬取时间</p><p>count = cur.execute(‘select * from allbooks’)</p><p>print(‘has %s record’ % count)#输出爬取的总数目条数</p><p># 释放数据连接</p><p>if cur:</p><p>cur.close()</p><p>if conn:</p><p>conn.close()</p><p>这样,一个程序就算完成了,豆瓣的书目信息就一条条地写进了我们的数据库中,当然,在爬取的过程中,也遇到了很多问题,比如标题返回的信息拆分后中会有空格,写入数据库中会出现错误,所以只截取了标题的之一部分,因而导致数据库中的一些书名不完整,过往的大神如果有什么办法,还请指教一二。</p><p>等待爬取的过程是漫长而又欣喜的,看着电脑上一条条信息被刷出来,成就感就不知不觉涌上心头;然而如果你吃饭时它在爬,你上厕所时它在爬,你都已经爬了个山回来了它还在爬时,便会有点崩溃了,担心电脑随时都会坏掉(还是穷学生换不起啊啊啊啊~)</p><h3 id="如何通过python操作xampp里面的MySQL数据库">如何通过python操作xampp里面的MySQL数据库</h3><p>您好,</p><p>import </p><p>MySQLdb</p><p>try:</p><p> conn=MySQLdb.connect(host=’localhost’,user=’root’,passwd=’root’,port=3306)</p><p> cur=conn.cursor()</p><p>conn.select_db(‘python’)</p><p>count=cur.execute(‘瞎脊select * </p><p>from test’磨仿渗)</p><p> print </p><p>‘there has %s rows record’ % count</p><p>result=cur.fetchone()</p><p> print </p><p>result</p><p> print </p><p>‘ID: %s info %s’ % result</p><p>results=cur.fetchmany(5)</p><p> for r in results:</p><p>print </p><p>r</p><p>print </p><p>‘==’*10</p><p> cur.scroll(0,mode=’absolute’)</p><p>results=cur.fetchall()</p><p> for r in results:</p><p>print </p><p>r</p><p><p>conn.commit()</p><p> cur.close()</p><p> conn.close()</p><p>except MySQLdb.Error,e:</p><p> print </p><p>“Mysql Error %d: %s”大握 % (e.args, e.args)python爬虫导入数据库的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于python爬虫导入数据库,Python爬虫的数据入库操作,如何用python爬取豆瓣读书的数据,如何通过python操作xampp里面的MySQL数据库的信息别忘了在本站进行查找喔。</p></div> <!--<p class="news"></p>--> <!--<div class="introBott" style="text-align: left;"> <h2><a href="http://fa12348.com/newslist/0数据库.html"></a></h2> </div>--> </div> </div> <div class="main-news"> <div class="layui-container"> <div class="layui-row layui-col-space20"> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368113631694848.html">微信连接服务器问题一直存在 (微信总是连不上服务器)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368073303461888.html">快速上手!阿里云备案服务号购买教程 (阿里云备案服务号购买)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368055087599616.html">应对虚拟主机数据库满了的解决方案 (虚拟主机数据库满了)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368039761612800.html">虚拟主机有哪些分类? (虚拟主机分类)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368024628563968.html">亚马逊云:轻松购买云服务器 (亚马逊云主机购买)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162368009944305664.html">阿里云主机实用教程:快速入门指南 (阿里云主机怎么用)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162367998405775360.html">网络中服务器的三种角色 (网络中的3种服务器角色是什么)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162367982488391680.html">阿里云App备案进度提升,快速通道开辟! (阿里云app备案进度)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162367969368608768.html">阿里云虚拟主机如何绑定二级域名? (阿里云虚拟主机绑定二级域名)</a> </div> </div> <div class="layui-col-lg6 content"> <div class="news-panel" style="padding-bottom:3px;width: auto"> <a href="http://fa12348.com/news/01162367954667573248.html">「推荐」Windows虚拟主机:实用高效的托管方案 (windows虚拟主机推荐)</a> </div> </div> </div> </div> </div> <!-- footer部分 --> <div class="footer"> <div class="layui-container"> <p class="footer-web"> </p> <div class="layui-row footer-contact"> <div class="layui-col-sm2 layui-col-lg1"><img width="90" height="90" src="https://global.cnd.aidufei.com/24114879/template/1323677109394214912.png"></div> <div class="layui-col-sm10 layui-col-lg11"> <div class="layui-row"> <div class="layui-col-sm6 layui-col-md8 layui-col-lg9"> <p class="contact-top"><i class="layui-icon layui-icon-cellphone"></i> 400-8888888 (9:00-18:00)</p> <p class="contact-bottom"><i class="layui-icon layui-icon-home"></i> gmail@qq.com</p> </div> <div class="layui-col-sm6 layui-col-md4 layui-col-lg3"> <p class="contact-top"><span class="right">© 祺平科技 • 版权所有</span></p> <p class="contact-bottom"><span class="right"> <a href="https://beian.miit.gov.cn" target="_blank">粤ICP备15012827号-5</a><br> <a href="https://zmcms.com" target="_blank">ZMCMS.COM</a> </span></p> </div> </div> </div> </div> </div> </div> <script src="https://global.cnd.aidufei.com/cms/lib/layui/layui.js"></script> <script> var path = 'https://global.cnd.aidufei.com/cms/'; var template = 't0_2'; layui.config({ base: path+'web/'+template+'/js/' }).use('firm'); </script><script> proxyImage('.introTop'); adjustImageSize('.introTop'); $(window).resize(function() {adjustImageSize('.introTop');}); </script> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?4234324324"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> </body> </html>