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计算已经过去多少个周末的方法。分享给大家供大家参考。具体如下: def weekends_between(d1,d2): days_between =...

使用 Python 实现微信群友统计器的思路详解

使用 Python 实现微信群友统计器的思路详解

基于微信可以做很多有意思的练手项目,看了这张速查表你就会发现,可以做的事情超过你的想象。 有一次我想要统计微信群里哪些同学在北京,但发现直接问是很难得到准确结果的…… 这时候不如运用...

Django 浅谈根据配置生成SQL语句的问题

想要根据django中的模型和配置生成SQL语句,需要先进行一定的设置: 首先需要在你的app文件夹中进入setting.py文件,里面有一个DATABASES,进行设置数据库的配置信息...

python sort、sort_index方法代码实例

本文实例为大家分享了python sort、sort_index的具体代码,供大家参考,具体内容如下 对Series进行排序 #生成序列obj obj=pd.Series([4,9...

使用Pytorch来拟合函数方式

其实各大深度学习框架背后的原理都可以理解为拟合一个参数数量特别庞大的函数,所以各框架都能用来拟合任意函数,Pytorch也能。 在这篇博客中,就以拟合y = ax + b为例(a和b为需...