美文网首页
Python2.7 Demos: 抓取百度百科

Python2.7 Demos: 抓取百度百科

作者: yanjf90 | 来源:发表于2016-08-25 22:59 被阅读0次

该demo以“百度百科”为关键字,抓取百科第一页搜索结果内容及其百科内容,并保存html 和 text 文件。

** 准备工作

打开[百度百科](http://baike.baidu.com title='baike'), 输入关键字“百度百科”,点击“搜索词条”按钮,在地址栏可找到搜索url: http://baike.baidu.com/search?word=百度百科&pn=0&rn=0&enc=utf8。由于关键字含有中文,有的word参数可能会进行url编码,后面我们会对此进行url解码。

打开开发者工具,查看源文件, 在97行可以找到如下源码,
<a class="result-title" href="http://baike.baidu.com/view/1.htm" target="_blank"><em>百度</em><em>百科</em>_百度百科</a>
其中href后面的地址就是对应词条的url。<a>标签之间的就是搜索到的词条,当然我们要把没用的html标签给replace掉。

** 正式开始

  1. 新建文件

在工作目录下创建baike/baike.py文件

  1. 文件编码

从搜索词条的url中enc参数可知,我们请求的文件编码格式为“utf8”, 所以我们文件格式也指定为“utf8”.
参考 Defining Python Source Code Encodings

  1. 定义变量

keyword:关键字
searchUrl: 搜索的url地址
quote(): url编码,需要导入urllib2库

  1. 抓取源文件

使用urllib2库抓取源文件

  1. 保存html文件
如果目录不存在,首先创建目录。
为了解决中文乱码问题,我们使用codecs库创建一个utf8格式的文件,把html内容写入文件时,也使用utf8编码,这样就不会乱码了(中文乱码搞了好久)。
open(), write(), close() 三步完活。
最后一个参数mode默认指定文件写的权限('w'), 后面还会使用追加('a')模式。
  1. 解析html
我们使用正则(re)模块解析下载下来的html。找到搜索到的关键词的title, url, summary,写入文件。
trimHtml() 去除提取到内容中的嵌套标签。这个函数有个缺陷就是只能处理单行,如果标签跨越多行,就无法处理。
  1. 主要逻辑

主要流程:查找url -> 抓取源文件 -> 保存html文件 -> 按行解析html -> 保存txt文件 -> 抓取搜索到的关键词源文件 -> 保存html文件 -> 解析html -> 保存txt文件

  1. 源码
#! /usr/bin/python
# -*- coding: utf8 -*-
import urllib2
import re
import os
import codecs 
def fetchSourceCode(url):
        response = urllib2.urlopen(url)
        return response.read()
def saveFile(path, filename, content, mode='w'):
        path = path.decode('utf8')
        filename = filename.decode('utf8')

        if not os.path.exists(path):
                os.makedirs(path)
        fd = codecs.open(path + "/" + filename, mode, 'utf8')
        fd.write(content.decode('utf8'))
        fd.close()
def matchResultTitle(line):
        match = re.match(r'.*?<a class="result-title" href="(.*?)" target="_blank">(.*?百度百科.*?)</a>.*', line)
        if match:
                return match.group(1), trimHtml(match.group(2))
        return None, None
def matchSummary(line):
        match = re.match(r'.*?<p class="result-summary">(.*?)</p>.*', line)
        if match:
                return trimHtml(match.group(1))
        return None
def findBodyContent(html):
        results = re.findall(r'<dd class="lemmaWgt-lemmaTitle-title">(.*?)</body>', html, re.S)
        if len(results) > 0:
                return trimHtml(results[0])
        return None
def trimHtml(text):
        return re.sub(r'<.*?>', '', text)
keyword = '百度百科'
searchUrl = 'http://baike.baidu.com/search?word=' + urllib2.quote('百度百科') + '&pn=0&rn=0&enc=utf8'
html = fetchSourceCode(searchUrl)
saveFile('baike', keyword + '.html', html)
saveFile('baike', keyword + '.txt', '')
lines = html.split('\n')
for line in lines:
        url, title = matchResultTitle(line)
        if url:
                saveFile('baike', keyword + '.txt', title + '\n' + url + '\n\n', mode='a')
                summary = matchSummary(line)
                if summary:
                        saveFile('baike', keyword + '.txt', summary + '\n\n', mode='a')
                # save sub html
                subHtml = fetchSourceCode(url)
                saveFile('baike/' + keyword, title + '.html', subHtml)
                bodyContent = findBodyContent(subHtml)
                saveFile('baike/' + keyword, title + '.txt', bodyContent)

相关文章

  • Python2.7 Demos: 抓取百度百科

    该demo以“百度百科”为关键字,抓取百科第一页搜索结果内容及其百科内容,并保存html 和 text 文件。 *...

  • 4-Answer 系列-本体构建模块(三)

    上一篇已经对百科百科的结构特点进行了分析,这一篇开始介绍本体构建模块的实现。 抓取百度百科 抓取百度百科页面数据自...

  • python抓取百度百科

    python抓取百度百科结构化信息 python从excel读取数据并将抓取到的数据存入excel

  • Python抓取百度百科数据

    抓取策略 确定目标:确定抓取哪个网站的哪些页面的哪部分数据。本实例抓取百度百科python词条页面以及python...

  • Python抓取百度百科数据

    抓取策略 确定目标:确定抓取哪个网站的哪些页面的哪部分数据。本实例抓取百度百科python词条页面以及python...

  • bzero(),bind(),listen(),accept()

    bzero_百度百科 bind()_百度百科 listen()_百度百科 accept()_百度百科

  • 爬虫基本原理

    爬虫基本原理 一、爬虫是什么? 百度百科和维基百科对网络爬虫的定义:简单来说爬虫就是抓取目标网站内容的工具,一般是...

  • 缘之空

    缘之空_百度百科 缘之空_百度百科 缘之空_百度百科 缘之空_百度百科 缘之空_百度百科 缘之空: 前言:嘿,大家...

  • 典籍摘录名称的说明(随时更新)

    参见百度百科-甄权 ↩ 参见百度百科-日华子诸家本草 ↩ 参见百度百科-唐容川 ↩ 参见百度百科-本草问答 ↩ 参...

  • 关于大数据的一些基本常识整理

    1.Hadoop生态 Hadoop生态圈介绍 Hadoop百度百科 MapReduce百度百科 Yarn百度百科 ...

网友评论

      本文标题:Python2.7 Demos: 抓取百度百科

      本文链接:https://www.haomeiwen.com/subject/eaensttx.html