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文件与目录操作实例详解

本文实例分析了python文件与目录操作的方法。分享给大家供大家参考,具体如下: 关于python文件操作的详细说明,大家可以参考前一篇《python文件操作相关知识点总结整理》 官方A...

python fabric实现远程操作和部署示例

近期接手越来越多的东西,发布和运维的工作相当机械,加上频率还蛮高,导致时间浪费还是优点多。修复bug什么的,测试,提交版本库(2分钟),ssh到测试环境pull部署(2分钟),rsync...

Python实现的弹球小游戏示例

Python实现的弹球小游戏示例

本文实例讲述了Python实现的弹球小游戏。分享给大家供大家参考,具体如下: 弹球 1. Ball 类 draw负责移动Ball 碰撞检测,反弹,Ball检测Paddle 2.Paddl...

python 处理数字,把大于上限的数字置零实现方法

如下所示: # coding=utf-8 # 用来处理数字,大于上限的数字置零 f = open("/home/chuwei/桌面/trainA/loss/d_losses.tx...

学Python 3的理由和必要性

Python很多年前就已经出现了,并且还在不断发展。本书第1版基 于Python 1.5.2,Python 2.x作为主流版本已经持续了很多年。本书是基 于Python 3.6的,并在P...