Python-爬取HTML网页数据

Python-爬取HTML网页数据

软件环境

  • Mac 10.13.1 (17B1003)
  • Python 2.7.10
  • VSCode 1.18.1

摘要

本文是练手Demo,主要是使用 Beautiful Soup 来爬取网页数据。

Beautiful Soup 介绍

Beautiful Soup提供一些简单的、python式的用来处理导航、搜索、修改分析树等功能。

Beautiful Soup 官方中文文档

特点

  • 简单:它是一个工具箱,通过解析文档为用户提供需要抓取的数据
  • Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。

Beautiful Soup 的安装

  • 安装 pip (如果需要): sudo easy_install pip
  • 安装 Beautiful Soup: sudo pip install beautifulsoup4

示例

确定获取数据范围

本示例是获取项目列表,打开Chrome的调试栏,找到对应的位置,如下图:
Chrome确定爬取位置

导包

import sys
import json
import urllib2 as HttpUtils
import urllib as UrlUtils
from bs4 import BeautifulSoup 

获取页面信息(分页)

def gethtml(page):
    '获取指定页码的网页数据'
    url = 'https://box.xxx.com/Project/List'
    values = {
        'category': '',
        'rate': '',
        'range': '',
        'page': page
    }
    data = UrlUtils.urlencode(values)
    # 使用 DebugLog
    httphandler = HttpUtils.HTTPHandler(debuglevel=1)
    httpshandler = HttpUtils.HTTPSHandler(debuglevel=1)
    opener = HttpUtils.build_opener(httphandler, httpshandler)
    HttpUtils.install_opener(opener)
    request = HttpUtils.Request(url + '?' + data)
    request.get_method = lambda: 'GET'
    try:
        response = HttpUtils.urlopen(request, timeout=10)
    except HttpUtils.URLError, err:
        if hasattr(err, 'code'):
            print err.code
        if hasattr(err, 'reason'):
            print err.reason
        return None
    else:
        print '====== Http request OK ======'
    return response.read().decode('utf-8')
TIPS
  • urlopen(url, data, timeout)
    • url: 请求的 URL
    • data: 访问 URL 时要传送的数据
    • timeout: 超时时间
  • HttpUtils.build_opener(httphandler, httpshandler)
    • 开启日志,将会在调试控制台输出网络请求日志,方便调试
  • 必要的 try-catch,以便可以捕获到网络异常

解析获取的数据

创建BeautifulSoup对象
soup = BeautifulSoup(html, 'html.parser')
获取待遍历的对象
# items 是一个 <listiterator object at 0x10a4b9950> 对象,不是一个list,但是可以循环遍历所有子节点。
items = soup.find(attrs={'class':'row'}).children
遍历子节点,解析并获取所需参数
projectList = []
for item in items:
    if item == '\n': continue
    # 获取需要的数据
    title = item.find(attrs={'class': 'title'}).string.strip()
    projectId = item.find(attrs={'class': 'subtitle'}).string.strip()
    projectType = item.find(attrs={'class': 'invest-item-subtitle'}).span.string
    percent = item.find(attrs={'class': 'percent'})
    state = 'Open'
    if percent is None: # 融资已完成
        percent = '100%'
        state = 'Finished'
        totalAmount = item.find(attrs={'class': 'project-info'}).span.string.strip()
        investedAmount = totalAmount
    else:
        percent = percent.string.strip()
        state = 'Open'
        decimalList = item.find(attrs={'class': 'decimal-wrap'}).find_all(attrs={'class': 'decimal'})
        totalAmount =  decimalList[0].string
        investedAmount = decimalList[1].string
    investState = item.find(attrs={'class': 'invest-item-type'})
    if investState != None:
        state = investState.string
    profitSpan = item.find(attrs={'class': 'invest-item-rate'}).find(attrs={'class': 'invest-item-profit'})
    profit1 = profitSpan.next.strip()
    profit2 = profitSpan.em.string.strip()
    profit = profit1 + profit2
    term = item.find(attrs={'class': 'invest-item-maturity'}).find(attrs={'class': 'invest-item-profit'}).string.strip()
    project = {
        'title': title,
        'projectId': projectId,
        'type': projectType,
        'percent': percent,
        'totalAmount': totalAmount,
        'investedAmount': investedAmount,
        'profit': profit,
        'term': term,
        'state': state
    }
    projectList.append(project)
输出解析结果,如下:

解析结果

TIPS




本文参考:
  • https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
  • http://www.jianshu.com/p/972c95610fdc
  • 16
    点赞
  • 146
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
爬虫(Web Crawler)是一种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据并存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,并模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,一些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,并确保对被访问网站的服务器负责。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值