Python爬虫基础入门实战案例(爬取网站小说)

案例使用Python3.7,pycharm2019

特别提醒:此案例仅是初学时案例,有很多不足,同时,阅读代码应当有Python3和基本的前端(HTML,js...)基础知识;

                  本案例对**小说网中的特定小说进行了爬取,随着网站的改进此代码可能失效

import requests #请求
import re #正则表达式模块
#from w3lib import html #
#from lxml import etree
#import urllib3 as ulb
#import numpy as np
import random

#下载一个网页
# url = 'https://www.jingcaiyuedu.com/novel/Ma9di.html'
url = 'https://www.jingcaiyuedu.com/novel/e4zfh2/list.html' #小说所有目录的页面的URL
#模拟浏览器发送HTTP请求报文

#避免网站反爬虫机制,加入header模拟浏览器想服务器发出请求,解决403 Forbiden的问题
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",}
response = requests.get(url, headers=headers)
#设置编码方式,防止乱码
response.encoding = 'utf-8'
#打印爬取结果或 成文本
#print(response.text)
#打印目标小说主页的网页源码,包含章节的超链接
html = response.text
#print(html)

#获取小说的title作为文件名
title = re.findall(r'<h1>(.*?)</h1>',html)[0]
#print(title)

#持久化,新建一个文件,写入小说内容,名称为小说名
fb = open('%s.txt' % title,'w',encoding='utf-8')


#获取每一章节的信息(章节,URL:在a标签中)
dl = re.findall(r'<dl class="panel-body panel-chapterlist">.*?</dl>',html,re.S)[0]
# print(dl)
#反向捕获章节的超链接和章节标题,生成的是一个list
chapter_info_list = re.findall(r'href="(.*?)">(.*?)<',dl)
# print(chapter_info_list)

#循环分离每一个章节的URL和标题下载
for chapter_info in chapter_info_list:
    # chapter_url =  chapter_info[0]
    # chapter_title = chapter_info[1]
    chapter_url,chapter_title = chapter_info #同时获取章节的URL和标题
    chapter_url = 'https://www.jingcaiyuedu.com%s' % chapter_url #拼接URL获得完整的章节的URL
    #print(chapter_url,chapter_title)
    # print(chapter_info_list)
    #下载章节的内容
    chapter_response = requests.get(chapter_url,headers=headers)
    chapter_response.encoding = 'utf-8'
    chapter_html = chapter_response.text #获取对应章节的网页代码
    #print(chapter_html)
    #提取章节内容
    chapter_content = re.findall(r'<div class="panel-body" id="htmlContent">(.*?)</div>',chapter_html,re.S)[0]
    #清洗数据

    chapter_content = chapter_content.replace('<p>', '\n') #替换换行标签保留换行样式
    chapter_content = chapter_content.replace('</p>', '')
    chapter_content = chapter_content.replace('<a>','')
    chapter_content = chapter_content.replace('</a>', '')
    chapter_content = chapter_content.replace(' ','')
    #print(chapter_content)
    fb.write(chapter_title)
    print('\n')
    fb.write(chapter_content)
    fb.write('\n')
    fb.write('\n')
    fb.write('\n')
    fb.write('\n')
    print(chapter_url)

 运行结果:产生一个以小说名字命名的txt文本,并向其中写入了小说的章节名称和内容

发布了17 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33360009/article/details/103996202