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 查看爬取结果。
第一步:
导入模块
- >>> import re
- >>> from bs4 import BeautifulSoup
- >>> 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
--------------------- 作者:iccool-cc 来源:CSDN 原文:https://blog.csdn.net/qq807237096/article/details/78794039?utm_source=copy 版权声明:本文为博主原创文章,转载请附上博文链接!