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中的XML库4Suite Server的介绍

在继续阅读本文之前,您务必要对我们在本专栏中将要讨论的一些技术有所了解。我们要使用的技术包括:可扩展的样式表语言转换(Extensible Stylesheet Language Tra...

浅谈pytorch grad_fn以及权重梯度不更新的问题

前提:我训练的是二分类网络,使用语言为pytorch Varibale包含三个属性: data:存储了Tensor,是本体的数据 grad:保存了data的梯度,本事是个Variable...

Python实现性能自动化测试竟然如此简单

Python实现性能自动化测试竟然如此简单

一、思考❓❔ 1.什么是性能自动化测试? 性能系统负载能力超负荷运行下的稳定性系统瓶颈自动化测试使用程序代替手工提升测试效率性能自动化使用代码模拟大...

python指定写入文件时的编码格式方法

实例如下: #encoding=utf-8 content=u"广东松炀再生资源股份有限" content=content.encode("utf-8")#写入的文件编码格式为utf...

Python之文字转图片方法

Python之文字转图片方法

Pygame模块一览表: 引入pygame模块 ,若本机没有请自行pip install pygame #载入必要的模块 import pygame #pygame初始化 pyga...