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

相关文章

pandas 对series和dataframe进行排序的实例

本问主要写根据索引或者值对series和dataframe进行排序的实例讲解 代码: #coding=utf-8 import pandas as pd import numpy a...

ubuntu17.4下为python和python3装上pip的方法

如果刚装上ubuntu会发现自带了python2和python3,但是发现系统没有带pip,所以输入下面的命令分别给他们装上pip: sudo apt-get install pyt...

利用Python实现Windows下的鼠标键盘模拟的实例代码

利用Python实现Windows下的鼠标键盘模拟的实例代码

本文介绍了利用Python实现Windows下的鼠标键盘模拟的实例代码,分享给大家 本来用按键精灵是可以实现我的需求,而且更简单,但既然学python ,就看一下呗。 依赖: PyUs...

PyQt5 实现字体大小自适应分辨率的方法

最近遇到一个现象,将做好的软件放在更高分辨率的电脑上运行,会导致字体显示不完全,出现被控件遮挡的情况。具体原因可以上网查询,在这里将记录下解决方法。 这里记录两种方法,如果使用的Qt版本...

python使用win32com库播放mp3文件的方法

本文实例讲述了python使用win32com库播放mp3文件的方法。分享给大家供大家参考。具体实现方法如下: # Python supports COM, if you have...