python采集百度百科的方法

yipeiwu_com6年前Python基础

本文实例讲述了python采集百度百科的方法。分享给大家供大家参考。具体如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#encoding=utf-8 
#Filename:get_baike.py
import urllib2,re
import sys
def getHtml(url,time=10):
 response = urllib2.urlopen(url,timeout=time)
 html = response.read()
 response.close()
 return html
def clearBlank(html):
 if len(html) == 0 : return ''
 html = re.sub('\r|\n|\t','',html)
 while html.find(" ")!=-1 or html.find(' ')!=-1 :
  html = html.replace(' ',' ').replace(' ',' ')
 return html
if __name__ == '__main__':
  html = getHtml('http://baike.baidu.com/view/4617031.htm',10)
  html = html.decode('gb2312','replace').encode('utf-8') #转码
  title_reg = r'<h1 class="title" id="[\d]+">(.*?)</h1>'
  content_reg = r'<div class="card-summary-content">(.*?)</p>'
  title = re.compile(title_reg).findall(html)
  content = re.compile(content_reg).findall(html)
  title[0] = re.sub(r'<[^>]*?>', '', title[0])
  content[0] = re.sub(r'<[^>]*?>', '', content[0])
  print title[0]
  print '#######################'
  print content[0]

希望本文所述对大家的Python程序设计有所帮助。

相关文章

详解python之heapq模块及排序操作

说到排序,很多人可能第一想到的就是sorted,但是你可能不知道python中其实还有还就中方法哟,并且好多种场景下效率都会比sorted高。那么接下来我就依次来介绍我所知道的排序操作。...

python对指定目录下文件进行批量重命名的方法

本文实例讲述了python对指定目录下文件进行批量重命名的方法。分享给大家供大家参考。具体如下: 这段python代码可对c:\temp目录下的所有文件名为”scroll_1”文件替换为...

分析python动态规划的递归、非递归实现

概要 本文只是简单的介绍动态规划递归、非递归算法实现 案例一 题目一:求数组非相邻最大和 [题目描述] 在一个数组arr中,找出一组不相邻的数字,使得最后的和最大。 [示例输入]...

利用matplotlib实现根据实时数据动态更新图形

利用matplotlib实现根据实时数据动态更新图形

我就废话不多说了,直接上代码吧! from time import sleep from threading importThread import numpy as np impo...

tornado捕获和处理404错误的方法

Tornado 文档中提到但是这样只能捕获到handlers中列出的路径请求中的错误。 如果只定义了(r"/hello", HelloHandler) 一条规则,那么只能捕获到 /hel...