起因
最近想离线看看小说,发现网上小说虽然有盗版网站,但是广告特别多,翻页也很麻烦,就在想能不能下载
找了一圈之后发现下载链接要么404要么就是广告,这时候只能用爬虫来解决了
计划方案
用BeautifulSoup抓取网页信息,然后写入到文件
BeautifulSoup使用
获取网页html元素
获取网页之后判断code码是否成功
if __name__ == '__main__':
resp = requests.get('https://www.shuhaige.net/46153/72134625.html')
print(resp.status_code)
print(resp.text)
返回结果:200
<!DOCTYPE html><html><head><meta charset="UTF-8"><me......
获取某个标签
from bs4 import BeautifulSoup
# 假设 HTML 内容
html_content = '''
<div id="A1">
<a class="C1" href="https://example.com">Link 1</a>
<a class="C2" href="https://other.com">Link 2</a>
</div>
'''
# 解析 HTML
soup = BeautifulSoup(html_content, 'html.parser')
# 查找 id 为 A1 的 div 元素
div_A1 = soup.find('div', id='A1')
# 查找 div_A1 中 class 为 C1 的 <a> 标签
link_C1 = div_A1.find('a', class_='C1')
# 获取 href 属性
url = link_C1['href'] if link_C1 else None
print(url) # 输出: https://example.com
##获取网页的想要的标题名称和段落
这样的标题获取就使用如下代码
soup = BeautifulSoup(response.text, 'html.parser')
bookName = soup.find(class_='bookname')
if bookName:
h1tag = bookName.find('h1')
if h1tag:
if h1tag.get_text() not in titleSet:
print(h1tag.get_text())
输出:第一章 开局一个民国位面
获取这样的内容使用
content = soup.find(id='content')
if content:
contentSplit = content.find_all('p')
if contentSplit:
for line in contentSplit:
print(line)
这样就能获取到文章的标题和内容。
下一页获取比较简单,他有固定的id=A3
nextPage = soup.find(id='A3')
print(nextPage['href'])
最后写入到文件就行
with open('testFile.txt', 'w', encoding='utf-8') as file:
# 写入内容
file.write(exportContent)
#最终版本
有几个问题最终版解决了,比如一个文章有多页,这样标题就会重复;频繁的拼接string,会导致变慢;文章内部有时候有广告性的文字,需要去除(还有一个未实现的,就是多线程并发去下载文章组合)
def version():
baseUrl = 'https://www.shuhaige.net'
pageUrl = '/46153/72134625.html'
bookContent = StringIO()
titleSet = set()
skipSet ={'小主,这个章节后面还有哦,请点击下一页继续阅读,后面更精彩!','这章没有结束,请点击下一页继续阅读!','本小章还未完,请点击下一页继续阅读后面精彩内容!','喜欢诸天从茅山开始请大家收藏:(www.shuhaige.net)诸天从茅山开始书海阁小说网更新速度全网最快。'}
# for i in range(3):
while pageUrl != '/shu_46153.html':
response = requests.get(baseUrl + pageUrl)
if response.status_code == 200:
print(response.text)
soup = BeautifulSoup(response.text, 'html.parser')
bookName = soup.find(class_='bookname')
if bookName:
h1tag = bookName.find('h1')
if h1tag:
if h1tag.get_text() not in titleSet:
# print(h1tag.get_text())
bookContent.write(h1tag.get_text())
titleSet.add(h1tag.get_text())
content = soup.find(id='content')
if content:
contentSplit = content.find_all('p')
if contentSplit:
for line in contentSplit:
# print(line)
if line.get_text() in skipSet:
continue
bookContent.write(line.get_text() + '\n')
nextPage = soup.find(id='A3')
# print(nextPage['href'])
pageUrl = nextPage['href']
else:
print('error:', response.text)
# 打开文件(如果文件不存在,会创建文件)
with open('testFile.txt', 'w', encoding='utf-8') as file:
# 写入内容
file.write(bookContent.getvalue())
print("内容已写入到 testFile.txt")