Python-爬取小说文字内容(使用beautiful soup实现)

 

Python-爬取小说文字内容(beautiful soup)

本次爬取的网站为[http://www.136book.com/][6],你可以在页面选择你想要爬取的小说。
文中代码使用Anaconda的Jupyter书写。

Beautiful Soup简介

官方解释:
Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。
Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。然后,你仅仅需要说明一下原始编码方式就可以了。
Beautiful Soup已成为和lxml、html6lib一样出色的python解释器,为用户灵活地提供不同的解析策略或强劲的速度。 —— [ beautiful soup ]

此次实战从网上爬取小说,需要使用到Beautiful Soup。
Beautiful Soup为python的第三方库,可以帮助我们从网页抓取数据。
它主要有如下特点:

1.Beautiful Soup可以从一个HTML或者XML提取数据,它包含了简单的处理、遍历、搜索文档树、修改网页元素等功能。可以通过很简短地代码完成我们地爬虫程序。
2.Beautiful Soup几乎不用考虑编码问题。一般情况下,它可以将输入文档转换为unicode编码,并且以utf-8编码方式输出。

对于本次爬虫任务,只要了解以下几点基础内容就可以完成:
1.Beautiful Soup的对象种类:
Tag
Navigablestring
BeautifulSoup
Comment
2.遍历文档树:find、find_all、find_next和children
3.一点点HTML和CSS知识(没有也将就,现学就可以)

Beautiful Soup安装

在Anaconda Prompt中输入:

pip install beautifulsoup4
  •  

安装beautiful soup。

使用python代码爬取

1.爬取思路分析

打开目录页,可以看到章节目录,想要爬取小说的内容,就要找到每个目录对应的url,并且爬取其中的正文内容,然后将正文内容取出来,放在本地文件中。这里选取《芈月传》作为示例。http://www.136book.com/mieyuechuanheji/

按F12查看网页的审查元素菜单,选择左上角[箭头]的标志,在目录中选择想要爬取的章节标题,如图:选择了【第六章 少司命(3)】,可以看到网页的源代码中,加深显示了本章的链接。

目录页章节的网页结构

这样我们可以看到,每一章的链接地址都是有规则地存放在<li>中。而这些<li>又放在<div id=”book_detail” class=”box1″>中。

2.单章节爬虫

刚才已经分析过网页结构。我们可以直接在浏览器中打开对应章节的链接地址,然后将文本内容提取出来。我们要爬取的内容全都包含在这个<div>里面。

单章节爬虫内容的网页结构

# 爬取单章节的文字内容
from urllib import request
from bs4 import BeautifulSoup

if __name__ == '__main__':
    # 第6章的网址
    url = 'http://www.136book.com/mieyuechuanheji/ewqlwb/'
    head = {}
    # 使用代理
    head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19'
    req = request.Request(url, headers = head)
    response = request.urlopen(req)
    html = response.read()
    # 创建request对象
    soup = BeautifulSoup(html, 'lxml')
    # 找出div中的内容
    soup_text = soup.find('div', id = 'content')
    # 输出其中的文本
    print(soup_text.text)

输出的结果为:
爬取第六章的结果

3.小说全集爬虫

思路是先在目录页中爬取所有章节的链接地址,然后再爬取每个链接对应的网页中的文本内容。说来,就是比单章节爬虫多一次解析过程,需要用到Beautiful Soup遍历文档树的内容。

1).解析目录页面

在思路分析中,我们已经了解了目录页的结构。所有的内容都放在一个所有的内容都放在一个<div id=”book_detail” class=”box1″>中。

代码整理如下:

# 爬取目录页面-章节对应的网址
from urllib import request
from bs4 import BeautifulSoup

if __name__ == '__main__':
    # 目录页
    url = 'http://www.136book.com/mieyuechuanheji/'
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19'
    req = request.Request(url, headers = head)
    response = request.urlopen(req)
    html = response.read()
    # 解析目录页
    soup = BeautifulSoup(html, 'lxml')
    # find_next找到第二个<div>
    soup_texts = soup.find('div', id = 'book_detail', class_= 'box1').find_next('div')
    # 遍历ol的子节点,打印出章节标题和对应的链接地址
    for link in soup_texts.ol.children:
        if link != '\n':
            print(link.text + ':  ', link.a.get('href'))

输出结果为:
爬取章节目录的结果

2).爬取全集内容

将每个解析出来的链接循环代入到url中解析出来,并将其中的文本爬取出来,并且写到本地E:/miyuezhuan.txt中。(存放位置可以根据自己的本地情况自定义)

代码整理如下:

# 爬取全集内容
from urllib import request
from bs4 import BeautifulSoup

if __name__ == '__main__':
    url = 'http://www.136book.com/mieyuechuanheji/'
    head = {}
    head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19'
    req = request.Request(url, headers = head)
    response = request.urlopen(req)
    html = response.read()
    soup = BeautifulSoup(html, 'lxml')
    soup_texts = soup.find('div', id = 'book_detail', class_= 'box1').find_next('div')
    # 打开文件
    f = open('E:/miyuezhuan.txt','w')
    # 循环解析链接地址
    for link in soup_texts.ol.children:
        if link != '\n':
            download_url = link.a.get('href')
            download_req = request.Request(download_url, headers = head)
            download_response = request.urlopen(download_req)
            download_html = download_response.read()
            download_soup = BeautifulSoup(download_html, 'lxml')
            download_soup_texts = download_soup.find('div', id = 'content')
            # 抓取其中文本
            download_soup_texts = download_soup_texts.text
            # 写入章节标题
            f.write(link.text + '\n\n')
            # 写入章节内容
            f.write(download_soup_texts)
            f.write('\n\n')
    f.close()

可以打开存放位置的文件:E:/miyuezhuan.txt 查看爬取结果。

 

 

第一步:

导入模块

 

  1. >>> import re  
  2. >>> from bs4 import BeautifulSoup  
  3. >>> import urllib.request 

-------------------------------------

第二步:

导入网址

url = "http://zsb.szu.edu.cn/zbs.html"  

-------------------------------------------------------------------------

第三步:

调动模块解析网址

>>> page = urllib.request.urlopen(url) #通过链接获取整个网页

>>> soup = BeautifulSoup(page,'lxml') #格式化排列

print(soup.prettify()) #打印出结构化的数据

第四步:

--------------------------------------------------------

-----------------------------------------------------------

下一步写,模拟浏览器的规格

 headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}

下一步,复制Xpath路径

/html/body/div[5]/table/tbody/tr/td[2]/div[3]/div[1]/div[2]/a

-----------------------------------------------------------

 

 

 

 

 

 

 

 

 

 

 

思路

  • 定时任务
  • 主程序
    • 爬取网页
    • 解析网页 获取所要内容
    • 存入表格
    • 绘图
    • 异常处理

如何实现定时爬取

# 定时任务
# 设定一个标签 确保是运行完定时任务后 再修改时间
flag = 0
# 获取当前时间
now = datetime.datetime.now()
# 启动时间
# 启动时间为当前时间 加5秒
sched_timer = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute,
                                now.second) + datetime.timedelta(seconds=5)
# 启动时间也可自行手动设置
# sched_timer = datetime.datetime(2017,12,13,9,30,10)
while (True):
    # 当前时间
    now = datetime.datetime.now()
    # print(type(now))
    # 本想用当前时间 == 启动时间作为判断标准,但是测试的时候 毫秒级的时间相等成功率很低 而且存在启动时间秒级与当前时间毫秒级比较的问题
    # 后来换成了以下方式,允许1秒之差
    if sched_timer < now < sched_timer + datetime.timedelta(seconds=1):
        time.sleep(1)


        # 主程序
        main()



        flag = 1
    else:
        # 标签控制 表示主程序已运行,才修改定时任务时间
        if flag == 1:
            # 修改定时任务时间 时间间隔为2分钟
            sched_timer = sched_timer + datetime.timedelta(minutes=2)
            flag = 0

代码(内带注释)

# -*- coding: utf-8 -*-
__author__ = 'iccool'

from bs4 import BeautifulSoup
import requests
from requests.exceptions import RequestException
import csv
import pandas as pd
import datetime
import time
import matplotlib.pyplot as plt
import random

# 设置中文显示
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号



# 由于只爬取两个网页的内容,就直接将该两个网页放入列表中
url_sell = 'https://otcbtc.com/sell_offers?currency=eth&fiat_currency=cny&payment_type=all'

url_buy = 'https://otcbtc.com/buy_offers?currency=eth&fiat_currency=cny&payment_type=all'
urls = [url_sell, url_buy]


# 更换User-Agent
def getHeaders():
    user_agent_list = [
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36',
        'Mozilla/5.0(Windows;U;WindowsNT6.1;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',
        'Mozilla/5.0(WindowsNT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1',      'Mozilla/4.0(compatible;MSIE7.0;WindowsNT5.1;Trident/4.0;SE2.XMetaSr1.0;SE2.XMetaSr1.0;.NETCLR2.0.50727;SE2.XMetaSr1.0)'
    ]
    index = random.randrange(0,len(user_agent_list))
    headers = {
        'User-Agent': user_agent_list[index]
    }
    return headers

# 获取页面内容
def getHtml(url):
    try:
        response = requests.get(url, headers=getHeaders())
        if response.status_code == 200:
            return response.text
    except RequestException:
        print('===request exception===')
        return None


# 解析网页 获取价格
def parse_html(html):
    try:
        soup = BeautifulSoup(html, 'lxml')
        price = soup.find("div", class_='can-buy-count').contents[0]
        price = float(str(price).strip().strip('\n').replace(',', ''))
        return price
    except Exception:
        print('===parseHtml exception===')
        return None


# 保存到csv表中
def save2csv(prices, sched_timer):
    with open('CNY-ETH.csv', 'a+', newline='', encoding='utf-8') as csvfile:
        writer = csv.writer(csvfile)
        # writer.writerow(['购买价格最低', '出售价格最低'])
        writer.writerow([sched_timer, prices[0], prices[1]])
    df = pd.read_csv('CNY-ETH.csv')
    print(df)


# 绘图
def drawPic():
    eth_file = pd.read_csv('CNY-ETH.csv')
    eth_file['DATE'] = pd.to_datetime(eth_file['DATE'])
    # print(eth_file.head(80))
    xlen = eth_file[0:120]
    plt.plot(eth_file['DATE'], xlen['购买价格最低'], c='g', ls='-')
    plt.plot(eth_file['DATE'], xlen['出售价格最低'], c='r', ls='-')
    plt.xticks(rotation=120)
    # plt.yticks(rotation=range(3400,3800))
    plt.xlabel('时间')
    plt.ylabel('价格')
    plt.title('CNY-ETH价格波动')
    # 由于plt.show()程序会停留不运行 ,采用以下方法,绘图后,停留15s,再关闭
    plt.ion()
    plt.pause(15)
    plt.close()

def main(sched_timer):
    prices = []
    for url in urls:
        html = getHtml(url)
        price = parse_html(html)
        if price == None:
            prices.append(None)
        else:
            prices.append(price)
    # print('购买价格最低:', prices[0],'\n出售价格最低:', prices[1])
    if prices[0] == None or prices[1] == None:
        print('===price has None===')
        pass
    else:
        save2csv(prices, sched_timer)
        drawPic()


if __name__ == '__main__':
    # 定时任务
    # 设定一个标签 确保是运行完定时任务后 再修改时间
    flag = 0
    # 获取当前时间
    now = datetime.datetime.now()
    # 启动时间
    # 启动时间为当前时间 加5秒
    sched_timer = datetime.datetime(now.year, now.month, now.day, now.hour, now.minute,
                                    now.second) + datetime.timedelta(seconds=5)
    # 启动时间也可自行手动设置
    # sched_timer = datetime.datetime(2017,12,13,9,30,10)
    while (True):
        # 当前时间
        now = datetime.datetime.now()
        # print(type(now))
        # 本想用当前时间 == 启动时间作为判断标准,但是测试的时候 毫秒级的时间相等成功率很低 而且存在启动时间秒级与当前时间毫秒级比较的问题
        # 后来换成了以下方式,允许1秒之差
        if sched_timer < now < sched_timer + datetime.timedelta(seconds=1):
            time.sleep(1)
            print(now)
            # 运行程序
            main(sched_timer)
            # 将标签设为 1
            flag = 1
        else:
            # 标签控制 表示主程序已运行,才修改定时任务时间
            if flag == 1:
                # 修改定时任务时间 时间间隔为2分钟
                sched_timer = sched_timer + datetime.timedelta(minutes=2)
                flag = 0

效果

能够成功获取信息,并插入表格,根据表格绘制图形。

DATE,购买价格最低,出售价格最低
2017-12-13 08:52:47,4515.93,4353.02
2017-12-13 08:53:47,4515.93,4353.02
2017-12-13 08:58:53,4516.0,4285.3
2017-12-13 08:59:53,4471.71,4267.73
2017-12-13 09:00:53,4471.71,4161.03
2017-12-13 09:01:53,4471.71,4267.76
2017-12-13 09:05:03,4439.7,4261.13
2017-12-13 09:06:03,4439.7,4289.99
2017-12-13 09:09:32,4416.94,4287.58
2017-12-13 09:11:32,4416.52,4287.58
2017-12-13 09:13:32,4401.11,4287.58
2017-12-13 09:15:32,4388.56,4269.03
2017-12-13 09:19:32,4375.76,4269.03
2017-12-13 09:25:33,4293.11,4244.36
2017-12-13 09:27:33,4293.1,4244.36
2017-12-13 09:29:33,4284.38,4202.34
2017-12-13 09:37:33,4284.56,4156.24
2017-12-13 09:39:33,4284.5,4156.18
2017-12-13 09:41:33,4284.5,4202.13
2017-12-13 09:47:33,4300.42,4151.83
2017-12-13 09:49:33,4291.85,4252.71
2017-12-13 09:53:33,4291.85,4232.38
2017-12-13 09:55:33,4320.55,4261.77
2017-12-13 09:57:33,4320.55,4261.77
2017-12-13 09:59:33,4320.55,4265.97
2017-12-13 10:01:33,4332.18,4277.45
2017-12-13 10:05:33,4331.0,4295.9
2017-12-13 10:17:18,4356.05,4322.61
2017-12-13 10:25:16,4272.99,4279.22
2017-12-13 10:41:45,4196.1,4163.88
2017-12-13 10:43:45,4200.18,4163.88
2017-12-13 10:45:45,4200.0,4174.56
2017-12-13 10:47:45,4200.0,4104.58
2017-12-13 10:49:45,4200.0,4104.61
2017-12-13 10:51:45,4190.0,4104.61
2017-12-13 10:59:45,4063.06,3984.8
2017-12-13 11:15:54,4200.0,4134.65
2017-12-13 11:17:54,4200.0,4134.65
2017-12-13 11:19:54,4200.0,4118.04
2017-12-13 11:21:54,4200.0,4118.04
2017-12-13 11:23:54,4197.94,4118.04
2017-12-13 11:27:54,4186.77,4107.08
2017-12-13 11:29:54,4186.52,4106.83
2017-12-13 11:31:54,4162.25,4107.24
2017-12-13 11:33:54,4162.25,4107.24
2017-12-13 11:35:54,4200.0,4131.92
2017-12-13 11:41:43,4200.2,4141.52
2017-12-13 11:43:43,4200.2,4141.52
2017-12-13 12:52:19,4198.0,4140.7
2017-12-13 13:33:01,4258.28,4216.2
2017-12-13 13:35:01,4259.0,4230.96
2017-12-13 13:47:02,4259.0,4218.04
2017-12-13 13:49:02,4258.98,4201.4
2017-12-13 13:51:02,4371.48,4205.84
2017-12-13 13:53:02,4259.0,4205.84
2017-12-13 13:55:02,4328.08,4203.23
2017-12-13 13:59:02,4288.99,4203.23
2017-12-13 14:01:02,4278.99,4215.75
2017-12-13 14:03:02,4253.35,4200.29
2017-12-13 14:03:30,4253.27,4200.29
2017-12-13 14:05:03,4236.82,4200.48
2017-12-13 14:07:06,4228.48,4183.35
2017-12-13 14:14:11,4189.99,4100.0
2017-12-13 14:19:13,4200.0,4101.37
2017-12-13 14:25:42,4238.39,4143.44
2017-12-13 14:27:42,4237.57,4143.44
2017-12-13 14:33:42,4259.31,4165.12
2017-12-13 14:36:50,4282.96,4206.91
2017-12-13 14:38:50,4270.65,4206.91
2017-12-13 14:42:50,4266.46,4206.97

CNY-ETH.png

--------------------- 作者:iccool-cc 来源:CSDN 原文:https://blog.csdn.net/qq807237096/article/details/78794039?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值