Python爬取CSDN博客内容

下载个人博客内容

可以是主页的内容, 也可以是每个分类下的内容

只需要把传入的URL地址修改一下就OK了

但是修改传入的URL时,记得检查一下如果 传入的URL 不带’?viewmode=contents‘, 那么只能得到五篇内容

[python]  view plain  copy
  1. #coding:utf-8  
  2. import webbrowser as web  
  3. import os  
  4. import time  
  5. import random  
  6. import urllib2,sys  
  7. from bs4 import BeautifulSoup  
  8. reload(sys)  
  9. sys.setdefaultencoding('utf-8')  
  10.   
  11. print ''''' 
  12.     本文下载CSDN个人博客下的内容 
  13. '''  
  14.   
  15.   
  16. #此地址根据实际情况修改,但是,记得最后要有 '?viewmode=contents' 否则每页显示内容有限  
  17. url = 'http://blog.csdn.net/qiqiyingse/article/category/6292432?viewmode=contents'  
  18. baseurl='http://blog.csdn.net'  
  19.   
  20.   
  21. def getPage(url): #伪装成浏览器登陆,获取网页源代码  
  22.       
  23.     headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}    
  24.     req = urllib2.Request(url=url,headers=headers)  
  25.     try:  
  26.         html = urllib2.urlopen(req).read()  
  27.     except urllib2.HTTPError,e:  
  28.         print e.code  
  29.         print e.reason  
  30.         #将网页内容传给BeautifulSoup解析  
  31.     return html  
  32.   
  33.   
  34. def geturl(html,url):  
  35.     urlList=[]  
  36.     #print html  
  37.     page = BeautifulSoup(html,'lxml')  
  38.     items = page.find_all('div',class_ ='list_item list_view')#找到每一个文章item  
  39.     ''''' 
  40.     if 'categor' in url: 
  41.         items = page.find_all('div',class_ ='list_item article_item') 
  42.     else: 
  43.         items = page.find_all('div',class_ ='list_item list_view') 
  44.     '''  
  45.     print len(items)  
  46.     for item in items:  
  47.         content=item.find('a')  
  48.         url=content.get('href')#找到每一个文章的连接  
  49.         url=baseurl+url#拼接成可访问的地址  
  50.         urlList.append(url)  
  51.     return urlList  
  52.   
  53. def getContent(html):  
  54.     page = BeautifulSoup(html,'lxml')  
  55.       
  56.     try:  
  57.         title=page.find('div',class_='article_title').find('a').text  
  58.         title=title.strip()  
  59.         print title  
  60.     except e:  
  61.         print e  
  62.       
  63.     try:  
  64.         content=page.find('div',class_='article_content')  
  65.         #print content.text  
  66.         with open(title+'.txt','w') as f:  
  67.             f.write(content.text)  
  68.     except e:  
  69.         print e  
  70.   
  71.   
  72.   
  73.   
  74. html=getPage(url)  
  75. urls=geturl(html,url)  
  76.   
  77. count=0  
  78. while count<len(urls):#根据文章列表的url决定循环次数,  
  79.     print (urls[count])  
  80.     htmltest=getPage(urls[count])  
  81.     getContent(htmltest)  
  82.     count=count+1  



重新追加一版

这个版本修正了一些错误

[python]  view plain  copy
  1. #coding:utf-8    
  2. import urllib2,re,time,random,os,datetime  
  3. import HTMLParser    
  4. from bs4 import BeautifulSoup    
  5. import sys    
  6. reload(sys)      
  7. sys.setdefaultencoding('utf-8')    
  8.     
  9.    
  10.     
  11. #自定义打印函数    
  12. def self_log(msg):    
  13.     print u'%s: %s' % (time.strftime('%Y-%m-%d %H:%M:%S'), msg)    
  14.     
  15. #获取页面内容    
  16. def  get_html(url):    
  17.     headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}    
  18.     req = urllib2.Request(url=url,headers=headers)    
  19.     try:    
  20.         html = urllib2.urlopen(req).read()  
  21. <span style="white-space:pre">  </span>html=HTMLParser.HTMLParser().unescape(html)  
  22.         return html           
  23.     except urllib2.HTTPError,e:    
  24.         print e.code    
  25.   
  26.         
  27. #得到博客页面总数    
  28. def get_last_page(html,fd):    
  29.     if not html:    
  30.         self_log(u'页面错误,停止运行')     
  31.         return    
  32.     page = BeautifulSoup(html,'lxml')    
  33.     try:  
  34.         last_page=page.find('div',class_ ='pagelist').find_all('a')    
  35.         last_page= last_page[len(last_page)-1].get('href')[-1:]    
  36.         self_log('总共有%s 页博客' % last_page)    
  37.         fd.write('总共有%s 页博客\n' % last_page)  
  38.         return last_page    
  39.     except Exception,e:    
  40.         return 1    
  41.   
  42.         
  43. #获取页面列表    
  44. def get_items(url):    
  45.     content_html=get_html(url)    
  46.     page = BeautifulSoup(content_html,'lxml')    
  47.     items = page.find_all('div',class_ ='list_item list_view')    
  48.     return items    
  49.     
  50. #根据每一个items list 提取需要的元素    
  51. def handle_items(items,content_list,read_num_for_sort):    
  52.     for item in items:    
  53.         temp={}#临时变量    
  54.             
  55.         title=item.find('a')#标题    
  56.         content_url='http://blog.csdn.net'+title.get('href')#标题对应文章的地址    
  57.         read_times=item.find('span',class_ ='link_view').text.strip()#阅读次数    
  58.         comments_time=item.find('span',class_ ='link_comments')#评论次数    
  59.             
  60.         read_number = int(filter(str.isdigit, str(read_times))) #提取出来具体阅读次数的数字,为之后的排序做准备    
  61.         read_num_for_sort.append(read_number)    
  62.     
  63.         #将数据打包    
  64.         temp['indexs']=read_number    
  65.         temp['title']=title.text.strip()    
  66.         temp['read_times']=read_times    
  67.         temp['comments_time']=comments_time.text.strip()    
  68.         temp['content_url']=content_url    
  69.         content_list.append(temp)    
  70.     
  71. #创建文件夹    
  72. def mkdir_folder(path):    
  73.     if not os.path.exists(path):      
  74.         os.makedirs(path)     
  75.     
  76. #获取页面信息    
  77. def getContent(html,dir_path):    
  78.     page = BeautifulSoup(html,'lxml')    
  79.     try:    
  80.         title=page.find('div',class_='article_title').find('a').text    
  81.         title=title.strip()    
  82.     except Exception,e:    
  83.         print e    
  84.     try:    
  85.         content=page.find('div',class_='article_content')    
  86.         dir_path=dir_path    
  87.         artitle_name_path=dir_path+'/'+title+'.txt'    
  88.         with open(artitle_name_path+'.txt','w') as f:    
  89.             f.write(content.text)    
  90.         self_log(u'存贮文章:%s 完毕' % title)    
  91.     except Exception,e:    
  92.         print e    
  93.     
  94. #存贮每一篇文章到本地    
  95. def run_to_get_article(content_total_list,dir_path):    
  96.     self_log('start save every article  ')    
  97.     for article_content in content_total_list:    
  98.         article_url=article_content.split('|')[4]    
  99.         self_log( '将要存贮的地址是: %s ...' % article_url)    
  100.         artitle_html=get_html(article_url)    
  101.         getContent(artitle_html,dir_path)    
  102.       
  103. #根据传进来的地址,获取博主名字,同时以博主名字命名存贮目录    
  104. def get_blocker_name(url):  
  105.     if 'viewmode' in url:  
  106.         print url.split('.net')[1]  
  107.         print url.split('.net')[1].split('?')[0].split('/')[1]  
  108.         return url.split('.net')[1].split('?')[0].split('/')[1]  
  109.     else:  
  110.         print url.split('.net')[1]  
  111.         print url.split('.net')[1].split('/')[1]            
  112.         return url.split('.net')[1].split('/')[1]            
  113. #程序运行主函数            
  114. def run(url,dir_path):    
  115.     read_num_for_sort=[]    
  116.     content_list=[]    
  117.     content_total_list=[]    
  118.         
  119.     #定义文件夹名字并创建文件夹    
  120.     dir_path=dir_path  
  121.     mkdir_folder(dir_path)    
  122.         
  123.     #定义文件名字    
  124.     count_file_name=dir_path+'/'+datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')+'.txt'    
  125.     fd=open(count_file_name,'w')    
  126.         
  127.     #1.从主页进入获取页面总数    
  128.     main_html=get_html(url)    
  129.     last_page=get_last_page(main_html,fd)    
  130.         
  131.   
  132.     if  last_page>1:  
  133.     #3.组装url,分别加载每页的页面,同时在每一个页面提取我们需要的内容    
  134.         for i in range(1,int(last_page)+1):    
  135.             if  'category' not in url:  
  136.                 main_url=url.split('?')[0]+'/article/list/%d?viewmode=contents' % i   
  137.             else:  
  138.                 main_url=url+'/%s' % i  
  139.             self_log('即将获取第%d页的内容,地址是:%s' % (i,main_url))    
  140.                     
  141.             items=get_items(main_url)#获取每一页的页面内容,根据页面内容得到文章item list    
  142.             handle_items(items,content_list,read_num_for_sort)#处理item list    
  143.     else:  
  144.         items=get_items(url)#获取每一页的页面内容,根据页面内容得到文章item list    
  145.         handle_items(items,content_list,read_num_for_sort)#处理item list    
  146.     self_log('总共有%d 篇文章' % len(content_list))#根据得到的数据,统计文章总数    
  147.     #根据 indexs(阅读次数)这个索引值进行排序    
  148.     #非常好的一个根据列表中字典数据进行排序的方法    
  149.     content_list = sorted(content_list,cmp=lambda x,y:cmp(x['indexs'],y['indexs']),reverse=0)    
  150.         
  151.     article_index = 1    
  152.     for a in content_list:    
  153.         #组装打印语句    
  154.         totalcontent= '第'+str(article_index)+'篇|'+a['title']+'|'+a['read_times']+'|'+a['comments_time']+'|'+a['content_url']    
  155.         #self_log(totalcontent)    
  156.         print totalcontent    
  157.         #将其存贮到本地    
  158.         fd.write(totalcontent)    
  159.         fd.write('\n')    
  160.         article_index +=1    
  161.         content_total_list.append(totalcontent)    
  162.     fd.close()          
  163.     
  164.     return content_total_list    
  165.         
  166. if __name__ == '__main__':     
  167.     print ''''' 
  168.             *****************************************   
  169.             **    Welcome to Spider of Count CSDN  **   
  170.             **      Created on 2017-05-07          **   
  171.             **      @author: Jimy_Fengqi           **   
  172.             ***************************************** 
  173.             '''  
  174.   
  175.     url='http://blog.csdn.net/qiqiyingse?viewmode=contents'    
  176.     #url='http://blog.csdn.net/qiqiyingse/article/category/6292432?viewmode=contents'   
  177.     #url='http://blog.csdn.net/zuoxiaolong8810/article/category/1434962?viewmode=contents'   
  178.     dir_path=get_blocker_name(url)  
  179.     content_total_list=run(url,dir_path)    
  180.     run_to_get_article(content_total_list,dir_path)    

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值