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程序设计有所帮助。

相关文章

使用PyCharm配合部署Python的Django框架的配置纪实

使用PyCharm配合部署Python的Django框架的配置纪实

安装软件 安装 Python 2.7、PyCharm、pip(Python包管理工具)、Django ( pip install Django) 部署 PyCharm 新建Django工...

django多种支付、并发订单处理实例代码

django实现多种支付方式 ''' #思路 我们希望,通过插拔的方式来实现多方式登录,比如新增一种支付方式,那么只要在项目中新增一个py文件,导入里面的pay方法就可以了...

在Django中创建动态视图的教程

在我们的`` current_datetime`` 视图范例中,尽管内容是动态的,但是URL ( /time/ )是静态的。 在 大多数动态web应用程序,URL通常都包含有相关的参数。...

Python 转义字符详细介绍

Python 转义字符 在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表: 原始字符串 有时我们并不想让转义字符生效,我们只想显示字符串原来的意思,这就要用r和...

Python3实现的字典、列表和json对象互转功能示例

本文实例讲述了Python3实现的字典、列表和json对象互转功能。分享给大家供大家参考,具体如下: python3可以使用json模块操作json json.dumps(): 对jso...