欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)批量下載新浪博客的方法

 更新時間:2015年06月15日 09:15:39   作者:秋風(fēng)秋雨  
這篇文章主要介紹了python實(shí)現(xiàn)批量下載新浪博客的方法,涉及Python頁面抓取的相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下

本文實(shí)例講述了python實(shí)現(xiàn)批量下載新浪博客的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

# coding=utf-8 
import urllib2
import sys, os
import re
import string
from BeautifulSoup import BeautifulSoup
def encode(s):
  return s.decode('utf-8').encode(sys.stdout.encoding, 'ignore')
def getHTML(url):
  #proxy_handler = urllib2.ProxyHandler({'http':'http://211.138.124.211:80'})
  #opener = urllib2.build_opener(proxy_handler)
  #urllib2.install_opener(opener)
  req = urllib2.Request(url)
  response = urllib2.urlopen(req, timeout=15)
  return BeautifulSoup(response, convertEntities=BeautifulSoup.HTML_ENTITIES)
def visible(element):
  '''抓取可見的文本元素'''
  if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
    return False
  elif re.match('<!--.*-->', str(element)):
    return False
  elif element == u'\xa0':
    return False
  return True
def delReturn(element):
  '''刪除元素內(nèi)的換行'''
  return re.sub('(?<!^)\n+(?!$)', ' ', str(element)).decode('utf-8')
def validFilename(filename):
  # windows
  return re.sub('[\/:*?<>"|\xa0]', '', filename)
def writeToFile(text, filename, dirname):
  if not os.path.exists(dirname):
    os.makedirs(dirname)
    print encode('保存到目錄'), dirname
  filename = validFilename(filename)
  print encode('保存文章'), filename
  path = os.path.join(dirname, filename)
  if not os.path.exists(path):
    f = open(path, 'w')
    f.write(text)
    f.close()
  else:
    print filename, encode('已經(jīng)存在')
def formatContent(url, title=''):
  '''格式化文章內(nèi)容'''
  page = getHTML(url)
  content = page.find('div', {'class':'articalContent'})
  art_id = re.search('blog_(\w+)\.html', url).group(1)
  blog_name = page.find('span', id='blognamespan').string
  if title == '':
    title = page.find('h2', id=re.compile('^t_')).string
  temp_data = filter(visible, content.findAll(text=True)) # 去掉不可見元素
  temp_data = ''.join(map(delReturn, temp_data)) # 刪除元素內(nèi)的換行符
  temp_data = temp_data.strip() # 刪除文章首尾的空行
  temp_data = re.sub('\n{2,}', '\n\n', temp_data) # 刪除文章內(nèi)過多的空行
  # 輸出到文件
  # 編碼問題
  temp_data = '本文地址:'.decode('utf-8') + url + '\n\n' + temp_data
  op_text = temp_data.encode('utf-8')
  op_file = title + '_' + art_id +'.txt'
  writeToFile(op_text, op_file, blog_name)
def articlelist(url):
  articles = {}
  page = getHTML(url)
  pages = page.find('ul', {'class':'SG_pages'}).span.string
  page_num = int(re.search('(\d+)', pages).group(1))
  for i in range(1, page_num+1):
    print encode('生成第%d頁文章索引'%i)
    if i != 1:
      url = re.sub('(_)\d+(\.html)$', '\g<1>'+str(i)+'\g<2>', url)
      page = getHTML(url)
    article = page.findAll('span', {'class':'atc_title'})
    for art in article:
      art_title = art.a['title']
      art_href = art.a['href']
      articles[art_title] = art_href
  return articles
def blog_dld(articles):
  if not isinstance(articles, dict):
    return False
  print encode('開始下載文章')
  for art_title, art_href in articles.items():
    formatContent(art_href, art_title)
if __name__ == '__main__':
  sel = raw_input(encode('你要下載的是(1)全部文章還是(2)單篇文章,輸入1或者2: '))
  if sel == '1':
    #articlelist_url = 'http://blog.sina.com.cn/s/articlelist_1303481411_0_1.html'
    articlelist_url = raw_input(encode('請輸入博客文章目錄鏈接: '))
    articles = articlelist(articlelist_url)
    blog_dld(articles)
  else:
    #article_url = 'http://blog.sina.com.cn/s/blog_4db18c430100gxc5.html'
    article_url = raw_input(encode('請輸入博客文章鏈接: '))
    formatContent(article_url)

希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

  • 詳解Python中數(shù)據(jù)類型的轉(zhuǎn)換

    詳解Python中數(shù)據(jù)類型的轉(zhuǎn)換

    這篇文章主要為大家詳細(xì)介紹了Python中數(shù)據(jù)類型轉(zhuǎn)換的相關(guān)資料,文中的示例代碼講解詳細(xì),具有一定的參考價值,感興趣的小伙伴可以了解一下
    2023-03-03
  • TensorFlow:將ckpt文件固化成pb文件教程

    TensorFlow:將ckpt文件固化成pb文件教程

    今天小編就為大家分享一篇TensorFlow:將ckpt文件固化成pb文件教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python logging.info在終端沒輸出的解決

    python logging.info在終端沒輸出的解決

    這篇文章主要介紹了python logging.info在終端沒輸出的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Python內(nèi)建屬性getattribute攔截器使用詳解

    Python內(nèi)建屬性getattribute攔截器使用詳解

    這篇文章主要為大家介紹了Python內(nèi)建屬性getattribute攔截器使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • 利用python獲取想要搜索的數(shù)據(jù)

    利用python獲取想要搜索的數(shù)據(jù)

    這篇文章主要介紹了利用Python爬蟲采集想要搜索的信息(利用某du的接口實(shí)現(xiàn))并且處理掉它的反爬手段,文中示例代碼很詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴快來一起學(xué)習(xí)吧
    2023-05-05
  • python 如何對Series中的每一個數(shù)據(jù)做運(yùn)算

    python 如何對Series中的每一個數(shù)據(jù)做運(yùn)算

    這篇文章主要介紹了python 實(shí)現(xiàn)對Series中的每一個數(shù)據(jù)做運(yùn)算操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-05-05
  • Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解

    Python Pandas數(shù)據(jù)分析之iloc和loc的用法詳解

    Pandas 是一個開放源碼、BSD 許可的庫,提供高性能、易于使用的數(shù)據(jù)結(jié)構(gòu)和數(shù)據(jù)分析工具,它是一個強(qiáng)大的分析結(jié)構(gòu)化數(shù)據(jù)的工具集,基礎(chǔ)是 Numpy
    2021-11-11
  • python中Lambda表達(dá)式詳解

    python中Lambda表達(dá)式詳解

    在本篇文章里小編給大家整理的是關(guān)于python中Lambda表達(dá)式的相關(guān)知識點(diǎn)內(nèi)容,有需要的朋友們可以學(xué)習(xí)下。
    2019-11-11
  • Python3+Appium實(shí)現(xiàn)多臺移動設(shè)備操作的方法

    Python3+Appium實(shí)現(xiàn)多臺移動設(shè)備操作的方法

    這篇文章主要介紹了Python3+Appium實(shí)現(xiàn)多臺移動設(shè)備操作的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • python-Web-flask-視圖內(nèi)容和模板知識點(diǎn)西寧街

    python-Web-flask-視圖內(nèi)容和模板知識點(diǎn)西寧街

    在本篇文章里小編給大家分享了關(guān)于python-Web-flask-視圖內(nèi)容和模板的相關(guān)知識點(diǎn)內(nèi)容,有需要的朋友們參考學(xué)習(xí)下。
    2019-08-08

最新評論