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中requests模块导入的问题

浅谈python中requests模块导入的问题

今天使用Pycharm来抓取网页图片时候,要导入requests模块,但是在pycharm中import requests 时候报错。 原因: python中还没有安装requests库...

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

django.db.utils.ProgrammingError: (1146, u“Table‘’ doesn’t exist”)问题的解决

一、现象 最近在数据库中删除了一张表,重新执行python manage.py migrate时出错,提示不存在这张表。通过查找相关的资料,最后找到了相关的解决方法,下面话不多说了,来一...

python打开网页和暂停实例

本文实例讲述了python打开网页和暂停的方法。分享给大家供大家参考。 具体实现代码如下: import webbrowser import os webbrowser.open_...

Python学习笔记整理3之输入输出、python eval函数

1. python中的变量: python中的变量声明不需要像C++、Java那样指定变量数据类型(int、float等),因为python会自动地根据赋给变量的值确定其类型。如 rad...

selenium+python截图不成功的解决方法

selenium+python,使用webdriver的截图函数get_screenshot_as_file()截图,代码如下: from selenium import webdr...