Python2.7 Demos: 抓取百度百科

该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)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,347评论 19 139
  • 1.创建文件夹 !/bin/sh mkdir -m 777 "%%1" 2.创建文件 !/bin/sh touch...
    BigJeffWang阅读 13,447评论 3 53
  • Python爬虫入门(urllib+Beautifulsoup) 本文包括:1、爬虫简单介绍2、爬虫架构三大模块3...
    廖少少阅读 13,336评论 0 6
  • 1 前言 作为一名合格的数据分析师,其完整的技术知识体系必须贯穿数据获取、数据存储、数据提取、数据分析、数据挖掘、...
    whenif阅读 18,169评论 45 523
  • 常想起那天,那个早上可能是我至今最清新的一个早上; 一个普通的周末,我回到了家,闲的蛋疼,想着要看日出;看日出这件...
    赵龙在学习阅读 1,144评论 2 0