python采集百度百科的方法

yipeiwu_com5年前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-tornado的接口用swagger进行包装的实例

python-tornado的接口用swagger进行包装的实例

写这个文章的主要原因,就是因为没有相关的东西,导致我完全不知道应该怎么做,经过了两个晚上的摸索,终于搞清楚了,如果有谁需要tornado+swagger的输出模式,可以照这个套; 主要是...

windows系统中python使用rar命令压缩多个文件夹示例

复制代码 代码如下:#!/usr/bin/env python# Filename: backup_ver1.py import osimport time # 1. The files...

详解如何利用Cython为Python代码加速

引言 通常,在 Python 中写循环(特别是多重循环)非常的慢,在文章 /post/133807.htm中,我们的元胞自动机的状态更新函数 update_state 使用了两重循环,所...

python缩进区别分析

仔细观察下面两个python程序,代码一模一样,但是运行的结果却不同,就是因为最后一行return缩进的不同复制代码 代码如下:def powersum(power, *args): '...

python3实现表白神器

本文实例为大家分享了使用python3制作的表白神器,供大家参考,具体内容如下 使用python3制作的小玩意,哪里需要改造的,望各位评论一下! #coding=utf-8 #第一个...