Python Selenium을 사용하여 콘텐츠를 크롤링하고 MySQL 데이터베이스를 저장하는 예제 다이어그램

高洛峰
풀어 주다: 2017-03-17 09:30:26
원래의
2180명이 탐색했습니다.

이 글에서는 주로 python 셀레늄 콘텐츠를 크롤링하고 MySQL 데이터베이스에 저장하는 구현 코드를 소개합니다. 필요한 친구들은

을 참고하면 됩니다. 이전 기사에서는 CSDN 블로그 요약 및 기타 정보를 크롤링하는 방법을 설명합니다. 일반적으로 Selenium 크롤러를 사용하여 데이터를 크롤링한 후 TXT 텍스트로 저장해야 하지만 이는 데이터 처리 및 데이터 분석을 수행하기 어렵습니다. 이번 글에서는 주로 Selenium을 통해 나의 개인 블로그 정보를 크롤링한 후 MySQL 데이터베이스에 저장하여 어느 시간대에 더 많은 블로그가 있는지 분석하고, WordCloud와 결합하여 글의 주제를 분석하는 등의 데이터 분석에 대해 설명합니다. 기사읽기순위 등 .
이 글은 기초적인 글이니 혹시나 내용에 오류나 부족한 점이 있으면 양해 부탁드립니다. 다음 글에서는 데이터 분석 과정을 간략하게 설명하겠습니다.

1. 크롤링 결과
크롤링된 주소는 http://blog.csdn.net/Eastmount

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



MySQL 데이터베이스에 크롤링하여 저장한 결과는 다음과 같습니다.

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


실행 과정은 다음과 같습니다. 아래 표시:

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

2. 전체 코드 분석

전체 코드는 다음과 같습니다.


# 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()
로그인 후 복사

크롤링할 사용자의 블로그 주소 URL을 Blog_Url.txt 파일에 아래 그림과 같이 넣어주세요. 여기서 작성자는 모든 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. 각 페이지의 정보를 크롤링합니다. 페이지를 반복하도록 URL을 설정합니다. 4. 다시 크롤링합니다.
'다음 페이지'를 클릭하여 이동할 수도 있습니다. '다음 페이지'가 없으면 점프가 중지되고 크롤러가 종료된 후 다음 블로거가 크롤링됩니다.

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

3. 세부정보 가져오기: 제목, 초록, 시간
그런 다음 Beaut를 사용하는 경우 요소를 검토하고 각 블로그 페이지를 분석합니다 ulSoup 크롤링이 "금지됨" 오류를 보고하는 경우.
각 기사는 아래와 같이

로 구성되어 있는 것으로 확인되며, 위치만 찾으시면 됩니다.

使用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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!