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如何求解两数的最大公约数

题目: 给定两个自然数,求这两个数的最大公约数。 分析: 单看题目的话,非常简单,我们可以循环遍历自然数,如果能够整除两个自然数,就把这个数记下来,在这些记录中找到最大的一个。 但...

Python PyQt5实现的简易计算器功能示例

Python PyQt5实现的简易计算器功能示例

本文实例讲述了Python PyQt5实现的简易计算器功能。分享给大家供大家参考,具体如下: 这里剩下计算函数(self.calculator)未实现,有兴趣的朋友可以实现它 【知识点】...

Python使用pandas和xlsxwriter读写xlsx文件的方法示例

Python使用pandas和xlsxwriter读写xlsx文件的方法示例

python使用pandas和xlsxwriter读写xlsx文件 已有xlsx文件如下: 1. 读取前n行所有数据 # coding: utf-8 import pandas a...

python实现音乐下载的统计

本文为大家分享了Python实现自己下载音乐统计的具体代码,供大家参考,具体内容如下 今天看Python实例,学习了如何对文件进行操作,突然想把自己网易云音乐下载到本地的歌曲名单写到一...

python中pytest收集用例规则与运行指定用例详解

前言 上篇文章相信大家已经了解了pytest在cmd下结合各种命令行参数如何运行测试用例,并输出我们想要看到的信息。那么今天会讲解一下pytest是如何收集我们写好的用例?我们又有哪些...