搜索
首页后端开发Python教程使用python Selenium爬取内容并存储MySQL数据库的实例图解

这篇文章主要介绍了python Selenium爬取内容并存储至MySQL数据库的实现代码,需要的朋友可以参考下

前面我通过一篇文章讲述了如何爬取CSDN的博客摘要等信息。通常,在使用Selenium爬虫爬取数据后,需要存储在TXT文本中,但是这是很难进行数据处理和数据分析的。这篇文章主要讲述通过Selenium爬取我的个人博客信息,然后存储在数据库MySQL中,以便对数据进行分析,比如分析哪个时间段发表的博客多、结合WordCloud分析文章的主题、文章阅读量排名等。
这是一篇基础性的文章,希望对您有所帮助,如果文章中出现错误或不足之处,还请海涵。下一篇文章会简单讲解数据分析的过程。

一. 爬取的结果
爬取的地址为:http://blog.csdn.net/Eastmount

使用python Selenium爬取内容并存储MySQL数据库的实例图解

        

        爬取并存储至MySQL数据库的结果如下所示:

使用python Selenium爬取内容并存储MySQL数据库的实例图解


        运行过程如下图所示:

使用python Selenium爬取内容并存储MySQL数据库的实例图解

二. 完整代码分析

完整代码如下所示:


# coding=utf-8 
 
from selenium import webdriver 
from selenium.webdriver.common.keys import Keys 
import selenium.webdriver.support.ui as ui   
import re
import time
import os
import codecs
import MySQLdb
 
#打开Firefox浏览器 设定等待加载时间 
driver = webdriver.Firefox()
wait = ui.WebDriverWait(driver,10) 

#获取每个博主的博客页面低端总页码  
def getPage():
 print 'getPage'
 number = 0  
 texts = driver.find_element_by_xpath("//p[@id='papelist']").text  
 print '页码', texts  
 m = re.findall(r'(\w*[0-9]+)\w*',texts) #正则表达式寻找数字  
 print '页数:' + str(m[1])  
 return int(m[1]) 
 
#主函数 
def main():
 #获取txt文件总行数
 count = len(open("Blog_URL.txt",'rU').readlines())
 print count
 n = 0
 urlfile = open("Blog_URL.txt",'r')

 #循环获取每个博主的文章摘信息 
 while n < count: #这里爬取2个人博客信息,正常情况count个博主信息
  url = urlfile.readline()
  url = url.strip("\n")
  print url
  driver.get(url)
  #获取总页码
  allPage = getPage()
  print u&#39;页码总数为:&#39;, allPage
  time.sleep(2)

  #数据库操作结合
  try:
   conn=MySQLdb.connect(host=&#39;localhost&#39;,user=&#39;root&#39;,
         passwd=&#39;123456&#39;,port=3306, db=&#39;test01&#39;)
   cur=conn.cursor() #数据库游标

   #报错:UnicodeEncodeError: &#39;latin-1&#39; codec can&#39;t encode character
   conn.set_character_set(&#39;utf8&#39;)
   cur.execute(&#39;SET NAMES utf8;&#39;)
   cur.execute(&#39;SET CHARACTER SET utf8;&#39;)
   cur.execute(&#39;SET character_set_connection=utf8;&#39;)
   
   #具体内容处理
   m = 1 #第1页
   while m <= allPage:
    ur = url + "/article/list/" + str(m)
    print ur
    driver.get(ur)
    
    #标题
    article_title = driver.find_elements_by_xpath("//p[@class=&#39;article_title&#39;]")
    for title in article_title:
     #print url
     con = title.text
     con = con.strip("\n")
     #print con + &#39;\n&#39;
    
    #摘要
    article_description = driver.find_elements_by_xpath("//p[@class=&#39;article_description&#39;]")
    for description in article_description:
     con = description.text
     con = con.strip("\n")
     #print con + &#39;\n&#39;

    #信息
    article_manage = driver.find_elements_by_xpath("//p[@class=&#39;article_manage&#39;]")
    for manage in article_manage:
     con = manage.text
     con = con.strip("\n")
     #print con + &#39;\n&#39;

    num = 0
    print u&#39;长度&#39;, len(article_title)
    while num < len(article_title):
     #插入数据 8个值
     sql = &#39;&#39;&#39;insert into csdn_blog
        (URL,Author,Artitle,Description,Manage,FBTime,YDNum,PLNum)
       values(%s, %s, %s, %s, %s, %s, %s, %s)&#39;&#39;&#39;
     Artitle = article_title[num].text
     Description = article_description[num].text
     Manage = article_manage[num].text
     print Artitle
     print Description
     print Manage
     #获取作者
     Author = url.split(&#39;/&#39;)[-1]
     #获取阅读数和评论数
     mode = re.compile(r&#39;\d+\.?\d*&#39;)
     YDNum = mode.findall(Manage)[-2]
     PLNum = mode.findall(Manage)[-1]
     print YDNum
     print PLNum
     #获取发布时间
     end = Manage.find(u&#39; 阅读&#39;)
     FBTime = Manage[:end]
     cur.execute(sql, (url, Author, Artitle, Description, Manage,FBTime,YDNum,PLNum)) 
     
     num = num + 1
    else:
     print u&#39;数据库插入成功&#39;    
    m = m + 1
     
  
  #异常处理
  except MySQLdb.Error,e:
   print "Mysql Error %d: %s" % (e.args[0], e.args[1])
  finally:
   cur.close() 
   conn.commit() 
   conn.close()
  
  n = n + 1
    
 else:
  urlfile.close()
  print &#39;Load Over&#39;
   
main()

在Blog_Url.txt文件中放置需要爬取用户的博客地址URL,如下图所示。注意在此处,作者预先写了个爬取CSDN所有专家的URL代码,这里为访问其他人用于提升阅读量已省略。

使用python Selenium爬取内容并存储MySQL数据库的实例图解

分析过程如下所示。
1.获取博主总页码
首先从Blog_Url.txt读取博主地址,然后访问并获取页码总数。代码如下:


#获取每个博主的博客页面低端总页码  
def getPage():
 print &#39;getPage&#39;
 number = 0  
 texts = driver.find_element_by_xpath("//p[@id=&#39;papelist&#39;]").text  
 print &#39;页码&#39;, texts  
 m = re.findall(r&#39;(\w*[0-9]+)\w*&#39;,texts) #正则表达式寻找数字  
 print &#39;页数:&#39; + str(m[1])  
 return int(m[1])

比如获取总页码位17页,如下图所示:

使用python Selenium爬取内容并存储MySQL数据库的实例图解

2.翻页DOM树分析
这里的博客翻页采用的是URL连接,比较方便。
如:http://blog.csdn.net/Eastmount/article/list/2
故只需要 :1.获取总页码;2.爬取每页信息;3.URL设置进行循环翻页;4.再爬取。
也可以采用点击"下页"跳转,没有"下页"停止跳转,爬虫结束,接着爬取下一个博主。

使用python Selenium爬取内容并存储MySQL数据库的实例图解

3.获取详细信息:标题、摘要、时间
然后审查元素分析每个博客页面,如果采用BeautifulSoup爬取会报错"Forbidden"。
发现每篇文章都是由一个e388a4556c0f65e1904146cc1a846bee94b3e26ee717c64999d7867364b1b4a3组成,如下所示,只需要定位到该位置即可。

使用python Selenium爬取内容并存储MySQL数据库的实例图解

        这里定位到该位置即可爬取,这里需要分别定位标题、摘要、时间。

使用python Selenium爬取内容并存储MySQL数据库的实例图解

代码如下所示。注意,在while中同时获取三个值,它们是对应的。


#标题
article_title = driver.find_elements_by_xpath("//p[@class=&#39;article_title&#39;]")
for title in article_title:
 con = title.text
 con = con.strip("\n")
 print con + &#39;\n&#39;
    
#摘要
article_description = driver.find_elements_by_xpath("//p[@class=&#39;article_description&#39;]")
for description in article_description:
 con = description.text
 con = con.strip("\n")
 print con + &#39;\n&#39;

#信息
article_manage = driver.find_elements_by_xpath("//p[@class=&#39;article_manage&#39;]")
for manage in article_manage:
 con = manage.text
 con = con.strip("\n")
 print con + &#39;\n&#39;

num = 0
print u&#39;长度&#39;, len(article_title)
while num < len(article_title):
 Artitle = article_title[num].text
 Description = article_description[num].text
 Manage = article_manage[num].text
 print Artitle, Description, Manage

 4.特殊字符串处理
获取URL最后一个/后的博主名称、获取字符串时间、阅读数代码如下:


#获取博主姓名
url = "http://blog.csdn.net/Eastmount"
print url.split(&#39;/&#39;)[-1]
#输出: Eastmount

#获取数字
name = "2015-09-08 18:06 阅读(909) 评论(0)"
print name
import re
mode = re.compile(r&#39;\d+\.?\d*&#39;) 
print mode.findall(name)
#输出: [&#39;2015&#39;, &#39;09&#39;, &#39;08&#39;, &#39;18&#39;, &#39;06&#39;, &#39;909&#39;, &#39;0&#39;]
print mode.findall(name)[-2]
#输出: 909


#获取时间
end = name.find(r&#39; 阅读&#39;)
print name[:end]
#输出: 2015-09-08 18:06

import time, datetime
a = time.strptime(name[:end],&#39;%Y-%m-%d %H:%M&#39;)
print a
#输出: time.struct_time(tm_year=2015, tm_mon=9, tm_mday=8, tm_hour=18, tm_min=6,
#  tm_sec=0, tm_wday=1, tm_yday=251, tm_isdst=-1)

三. 数据库相关操作
SQL语句创建表代码如下:


CREATE TABLE `csdn` (
 `ID` int(11) NOT NULL AUTO_INCREMENT,
 `URL` varchar(100) COLLATE utf8_bin DEFAULT NULL,
 `Author` varchar(50) COLLATE utf8_bin DEFAULT NULL COMMENT &#39;作者&#39;,
 `Artitle` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT &#39;标题&#39;,
 `Description` varchar(400) COLLATE utf8_bin DEFAULT NULL COMMENT &#39;摘要&#39;,
 `Manage` varchar(100) COLLATE utf8_bin DEFAULT NULL COMMENT &#39;信息&#39;,
 `FBTime` datetime DEFAULT NULL COMMENT &#39;发布日期&#39;,
 `YDNum` int(11) DEFAULT NULL COMMENT &#39;阅读数&#39;,
 `PLNum` int(11) DEFAULT NULL COMMENT &#39;评论数&#39;,
 `DZNum` int(11) DEFAULT NULL COMMENT &#39;点赞数&#39;,
 PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9371 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

显示如下图所示:

使用python Selenium爬取内容并存储MySQL数据库的实例图解

其中,Python调用MySQL推荐下面这篇文字。
python专题九.Mysql数据库编程基础知识
核心代码如下所示:


# coding:utf-8 
import MySQLdb
 
try:
 conn=MySQLdb.connect(host=&#39;localhost&#39;,user=&#39;root&#39;,passwd=&#39;123456&#39;,port=3306, db=&#39;test01&#39;)
 cur=conn.cursor()
 
 #插入数据
 sql = &#39;&#39;&#39;insert into student values(%s, %s, %s)&#39;&#39;&#39;
 cur.execute(sql, (&#39;yxz&#39;,&#39;111111&#39;, &#39;10&#39;))

 #查看数据
 print u&#39;\n插入数据:&#39;
 cur.execute(&#39;select * from student&#39;)
 for data in cur.fetchall():
  print &#39;%s %s %s&#39; % data
 cur.close()
 conn.commit()
 conn.close()
except MySQLdb.Error,e:
  print "Mysql Error %d: %s" % (e.args[0], e.args[1])

注意,在下载过程中,有的网站是新版本的,无法获取页码。
比如:http://blog.csdn.net/michaelzhou224
这时需要简单设置,跳过这些链接,并保存到文件中,核心代码如下所示:


#获取每个博主的博客页面低端总页码  
def getPage():
 print &#39;getPage&#39;
 number = 0  
 #texts = driver.find_element_by_xpath("//p[@id=&#39;papelist&#39;]").text
 texts = driver.find_element_by_xpath("//p[@class=&#39;pagelist&#39;]").text
 print &#39;testsss&#39;
 print u&#39;页码&#39;, texts
 if texts=="":
  print u&#39;页码为0 网站错误&#39;
  return 0
 m = re.findall(r&#39;(\w*[0-9]+)\w*&#39;,texts) #正则表达式寻找数字  
 print u&#39;页数:&#39; + str(m[1])  
 return int(m[1])

主函数修改:


 error = codecs.open("Blog_Error.txt", &#39;a&#39;, &#39;utf-8&#39;)

 #循环获取每个博主的文章摘信息 
 while n < count: #这里爬取2个人博客信息,正常情况count个博主信息
  url = urlfile.readline()
  url = url.strip("\n")
  print url
  driver.get(url+"/article/list/1")
  #print driver.page_source
  #获取总页码
  allPage = getPage()
  print u&#39;页码总数为:&#39;, allPage
  #返回错误,否则程序总截住
  if allPage==0:
   error.write(url + "\r\n")
   print u&#39;错误URL&#39;
   continue; #跳过进入下一个博主
  time.sleep(2)
  #数据库操作结合
  try:
    .....

以上是使用python Selenium爬取内容并存储MySQL数据库的实例图解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

阵列的同质性质如何影响性能?阵列的同质性质如何影响性能?Apr 25, 2025 am 12:13 AM

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

编写可执行python脚本的最佳实践是什么?编写可执行python脚本的最佳实践是什么?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy数组与使用数组模块创建的数组有何不同?Numpy数组与使用数组模块创建的数组有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

Numpy数组的使用与使用Python中的数组模块阵列相比如何?Numpy数组的使用与使用Python中的数组模块阵列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模块与Python中的数组有何关系?CTYPES模块与Python中的数组有何关系?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器