美文网首页
python学习 从网页上下载一整本小说的完整代码

python学习 从网页上下载一整本小说的完整代码

作者: 八重代 | 来源:发表于2019-12-26 16:55 被阅读0次
import requests
from parsel import Selector

#将一章小说写入txt中封装成一个函数
def download_one(url):
    res = requests.get(url) # 爬取网站

    res.encoding = res.apparent_encoding # 设置编码

    html = res.text

    sel = Selector(html)
    #获取的一章的标题
    title = sel.css('h1::text').get()
    #测试.txt是我本地就有的文件,我直接打开追加写入就好了
    f=open('测试.txt',mode='a',encoding='utf-8')

    f.write(title)

    #获取的一章的内容
    for line in sel.css('#content p::text').getall():
        print(line.strip(),file=f)

    #关闭文件
    f.close()


url = '小说目录网址'

res = requests.get(url) # 爬取网站

res.encoding = res.apparent_encoding # 设置编码

html = res.text

sel = Selector(html)

#查看网站的css,找到目录里面的节点
charpter = sel.css('.chapterlist ul li a::attr(href)').getall()

#download_one('网址')

#根据这个目录网址找到规律,找到每章的地址,调用封装好的方法即可
for index in charpter:
    print('网址'+index)
    download_one('网址'+index)


相关文章

网友评论

      本文标题:python学习 从网页上下载一整本小说的完整代码

      本文链接:https://www.haomeiwen.com/subject/wplloctx.html