Skip to content

Commit 442b6cf

Browse files
committed
docs: 新增文档 利用python实现小说自由
新增文档 利用python实现小说自由
1 parent 69ea812 commit 442b6cf

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
### 利用python实现小说自由
2+
3+
#### 一、用到的相关模块
4+
5+
1.reuqests模块
6+
7+
安装reuqest模块,命令行输入:
8+
9+
```
10+
pip install requests
11+
```
12+
13+
2.xpath解析
14+
15+
​ XPath 即为 XML 路径语言,它是一种用来确定 XML (标准通用标记语言子集)文档中某部分位置的语言。XPath 基于 XML 的树状结构,提供在数据结构树中找寻节点的能力。起初 XPath 的提出的初衷是将其作为一个通用的、介于 XPointer 与 XSL 间的语法模型。但是 XPath 很快的被开发者采用来当作小型查询语言。
16+
17+
​ 简单的来说:Xpath(XML Path Language)是一门在 XML 和 HTML 文档中查找信息的语言,可用来在 XML 和 HTML 文档中对元素和属性进行遍历。
18+
19+
​ xml 是 一个HTML/XML的解析器,主要的功能是如何解析和提取 HTML/XML 数据。
20+
21+
安装xml:
22+
23+
```
24+
pip install lxml
25+
```
26+
27+
28+
29+
#### 二、实现步骤
30+
31+
1.首先我们打开一个小说的网址:https://www.qu-la.com/booktxt/17437775116/
32+
33+
2.右击“检查” 查看下这个网页的相关代码情况
34+
35+
<img src="https://s2.loli.net/2024/03/01/y3XolKRDgu6VJbj.png">
36+
37+
我们可以发现所有的内容都被包裹在<ul class="cf”> 的ul中。
38+
39+
右击复制出xpath路径
40+
41+
//*[@id="list"]/div[3]/ul[2]
42+
43+
<img src="https://s2.loli.net/2024/03/01/kzjRUCqwheHxFuY.png"/>
44+
45+
通过xpath 解析出每个章节的标题,和链接。
46+
47+
3.根据对应的链接获取每个章节的文本。同样的方法找到章节文本的具体位置
48+
49+
//*[@id="txt"]
50+
51+
<img src="https://s2.loli.net/2024/03/01/1j5FktPoXpcnUJi.png"/>
52+
53+
3.for 循环获取所有链接的文本,保存为Txt文件。
54+
55+
#### 三、代码展示
56+
57+
```python
58+
import requests
59+
from lxml import etree
60+
def getNovel():
61+
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36'};
62+
html = requests.get('https://www.qu-la.com/booktxt/17437775116/',headers=headers).content
63+
doc=etree.HTML(html)
64+
contents=doc.xpath('//*[ @id="list"]/div[3]/ul[2]') #获取到小说的所有章节
65+
for content in contents:
66+
links=content.xpath('li/a/@href') #获取每个章节的链接
67+
for link in links: #循环处理每个章节
68+
url='https://www.qu-la.com'+link #拼接章节url
69+
html=requests.get(url).text
70+
doc=etree.HTML(html)
71+
content = doc.xpath('//*[@id="txt"]/text()') #获取章节的正文
72+
title = doc.xpath('//*[@id="chapter-title"]/h1/text()') #获取标题
73+
#所有的保存到一个文件里面
74+
with open('books/凡人修仙之仙界篇.txt', 'a') as file:
75+
file.write(title[0])
76+
print('正在下载{}'.format(title[0]))
77+
for items in content:
78+
file.write(item)
79+
80+
print('下载完成')
81+
getNovel() #调用函数
82+
```
83+
84+
#### 四、拓展思考
85+
86+
1.写一个搜索界面,用户输入书名自主下载对应的小说。
87+
88+
2.引入多进程异步下载,提高小说的下载速度。
89+
90+
91+

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy