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 语言的优点 目前,Python 在各领域都有着广泛的应用。由此...

python读取文本中数据并转化为DataFrame的实例

python读取文本中数据并转化为DataFrame的实例

在技术问答中看到一个这样的问题,感觉相对比较常见,就单开一篇文章写下来。 从纯文本格式文件 “file_in”中读取数据,格式如下: 需要输出成“file_out”,格式如下: 数据...

pytorch cnn 识别手写的字实现自建图片数据

pytorch cnn 识别手写的字实现自建图片数据

本文主要介绍了pytorch cnn 识别手写的字实现自建图片数据,分享给大家,具体如下: # library # standard library import os # th...

Python 分享10个PyCharm技巧

Python 分享10个PyCharm技巧

# 0. PyCharm 常用快捷键 # 1. 查看使用库源码 PyCharm 主程序员在 Stackoverflow 上答道 经常听人说,多看源码。源码不仅能帮我们搞清楚运行机制...

Python3删除排序数组中重复项的方法分析

本文实例讲述了Python3删除排序数组中重复项的方法。分享给大家供大家参考,具体如下: 给定一个排序数组,你需要在[原地]删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新...