How to batch download Sina blogs using python

Source: Internet
Author: User
This article mainly introduces how to download Sina blogs in batches using python, and involves implementation skills related to Python page capturing, for more information about how to download Sina blogs in batches using python, see the following example. Share it with you for your reference. The specific implementation method is as follows:

# Coding = UTF-8 import urllib2import sys, osimport reimport stringfrom BeautifulSoup import BeautifulSoupdef 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 = response (req, timeout = 15) return BeautifulSoup (response, convertEntities = BeautifulSoup. HTML_ENTITIES) def visible (element): ''' capture the visible text 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 Truedef delReturn (element ): '''delete line breaks in the element ''' return re. sub ('(?
 "| \ Xa0] ','', filename) def writeToFile (text, filename, dirname): if not OS. path. exists (dirname): OS. makedirs (dirname) print encode ('Save to directory'), dirname filename = validFilename (filename) print encode ('Save the article '), 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 ('already exists') def formatContent (url, title = ''): ''' Formatting the article content ''' page = getHTML (url) content = page. find ('P', {'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) # Remove the invisible element temp_data = ''. join (map (delReturn, temp_data) # Delete the line break in the element temp_data = te Mp_data.strip () # Delete the empty row temp_data = re. sub ('\ n {2,}', '\ n \ n', temp_data) # Delete too many blank lines in the article # output to the file # encoding problem temp_data =' address of this article: '. 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 ('generate Article index on Page % 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 articlesdef blog_dld (articles): if not isinstance (articles, dict): return False print encode ('start downloading ') for art_title, art_href in articles. items (): formatContent (art_href, art_title) if _ name _ = '_ main __': sel = raw_input (encode ('Do you want to download (1) all articles or (2) single article, input 1 or 2: ') if sel = '1 ': # articlelist_url =' http://blog.sina.com.cn/s/articlelist_1303481411_0_1.html 'Articlelist_url = raw_input (encode ('Enter the blog article directory link: ') articles = articlelist (articlelist_url) blog_dld (articles) else: # article_url =' http://blog.sina.com.cn/s/blog_4db18c430100gxc5.html 'Article_url = raw_input (encode ('Enter the blog post link: ') formatContent (article_url)

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.