假设各位老哥已经安装好了bs4 requests这些库了

这个小说是随便挑的,各位也就不用太介意(仅供各位学习)

python3 实现,网上用python2做爬虫的太多了,但用python3的还是比较少

虽说步骤四 是脱胎于之前的三个步骤,但确实为了更进一步而做的一点小突破

这步骤四中,将会爬取小说对对应的目录链接。

通过步骤四中 寻找到的那些url来对逐步访问,获取txt并写入(这个在之前也都讲过了)

没有看过 步骤一 的朋友们可以点击下面的链接看看步骤一先

点击查看步骤一

没有看过 步骤二 的朋友们可以点击下面的链接看看步骤二先

点击查看步骤二

没有看过 步骤三 的朋友们可以点击下面的链接看看步骤三先

点击查看步骤三

获取整部小说的章节数目

通过目录来进行判断,将那些跟小说无关的章节 筛选掉

现在有点晚了,先发一个获取到的目录代码,后续明早在后面补充。有兴趣的朋友可以点 ‘喜欢’ 这样就可以保存文章链接在之后的喜欢栏中接着看了。(我蛮喜欢这样做的hihi)

代码 版本一效果图

代码 版本一

import requests
from bs4 import BeautifulSoup
content_url = "http://www.biquge.com.tw/4_4038/"
kv = {'user_agent': 'Mozilla/5.0'} # 表示是一个浏览器
try:
r = requests.get(content_url, headers=kv)
r.raise_for_status()
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'html.parser')
content_list = soup.find(id='list')
chapter_list = soup.find_all('dd')
for chapter in chapter_list:
print(chapter.find('a').text)
except:
pass

代码 版本二(新版)

import requests
from bs4 import BeautifulSoup
urls = []
title = []
content_url = "http://www.biquge.com.tw/4_4038"
kv = {'user_agent': 'Mozilla/5.0'} # 表示是一个浏览器
book_name = '1.txt' # 设置一个Default书名(虽然在后来肯定是会找到一个名字的)
try:
r = requests.get(content_url, headers=kv) # 表示自己是一个浏览器
r.raise_for_status() # 如果有问题就会raise一个问题
r.encoding = r.apparent_encoding # 根据网页返回的编码 进行调整
soup = BeautifulSoup(r.text, 'html.parser')
content_list = soup.find(id='list')
chapter_list = soup.find_all('dd')
meta = soup.find('head').find(attrs={'property': "og:novel:book_name"})
book_name = meta['content'] + '.txt'
print(book_name[:book_name.index('.txt')] + '写入中')
for chapter in chapter_list: # 整合得到所有跟内容有关的链接(会有哪些跟内容无关的章节的)
if '第' in chapter.find('a').text and '章' in chapter.find('a').text:
title.append(chapter.find('a').text)
urls.append(content_url[:content_url.rindex('/')] + chapter.find('a')['href'])
except:
pass