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 numpy实现二维数组和一维数组拼接的方法

撰写时间:2017.5.23 一维数组 1.numpy初始化一维数组 a = np.array([1,2,3]); print a.shape 输出的值应该为(3,) 二维数组 2...

Python中用Ctrl+C终止多线程程序的问题解决

复制代码 代码如下:#!/bin/env python # -*- coding: utf-8 -*- #filename: peartest.py imp...

Python实现SQL注入检测插件实例代码

Python实现SQL注入检测插件实例代码

扫描器需要实现的功能思维导图 爬虫编写思路 首先需要开发一个爬虫用于收集网站的链接,爬虫需要记录已经爬取的链接和待爬取的链接,并且去重,用 Python 的set()就可以解决,大概...

sklearn-SVC实现与类参数详解

sklearn-SVC实现与类参数 对应的API:http://scikit-learn.sourceforge.net/stable/modules/generated/sklearn...

python 判断一个进程是否存在

源代码如下:复制代码 代码如下:#-*- coding:utf-8 -*- def check_exsit(process_name): import win32com.client W...