前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python爬虫练习 爬取网络小说保存到txt

Python爬虫练习 爬取网络小说保存到txt

作者头像
叶庭云
修改2021-01-23 14:11:09
5.4K1
修改2021-01-23 14:11:09
举报
文章被收录于专栏:Python进阶之路Python进阶之路

利用python爬虫爬取网络小说保存到txt,熟悉利用python抓取文本数据的方法。

以爬取《伏天氏》这本小说的章节内容为例,目标url:http://www.xbiquge.la/0/951/

选取其中某一章,检查网页,可以找到这本小说所有章节的链接和名称。

写出xpath表达式提取出href里的内容://div@id=“list”/dl/dd/a/@href

分析网页可得,提取出来的内容里每个元素前面应加上 http://www.xbiquge.la 得到的才是是每个章节真正的链接

抓取所有章节的链接,代码如下:

代码语言:txt
复制
def get_urls():
    url = "http://www.xbiquge.la/0/951/"
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    html = etree.HTML(response.text)
    # 所有章节的url列表
    url_list = ['http://www.xbiquge.la' + x for x in html.xpath('//div[@id="list"]/dl/dd/a/@href')]
    return url_list

抓取每章的章节名称和内容保存到txt,代码如下:

代码语言:txt
复制
def get_text(url):
    rep = requests.get(url, headers=headers)
    rep.encoding = 'utf-8'
    dom = etree.HTML(rep.text)
    name = dom.xpath('//div[@class="bookname"]/h1/text()')[0]
    text = dom.xpath('//div[@id="content"]/text()')
    with open(path + f'{name}.txt', 'w', encoding='utf-8') as f:
        for con in text:
            f.write(con)
    print(f'{name} 下载完成')

完整代码如下:

代码语言:txt
复制
import requests
from lxml import etree
import time
import random

path = r'D:\test\伏天氏\ '
headers = {
    "Referer": "http://www.xbiquge.la/0/951/",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1"
}

def get_urls():
    url = "http://www.xbiquge.la/0/951/"
    response = requests.get(url, headers=headers)
    response.encoding = 'utf-8'
    html = etree.HTML(response.text)
    # 所有章节的url列表
    url_list = ['http://www.xbiquge.la' + x for x in html.xpath('//div[@id="list"]/dl/dd/a/@href')]
    return url_list

def get_text(url):
    rep = requests.get(url, headers=headers)
    rep.encoding = 'utf-8'
    dom = etree.HTML(rep.text)
    name = dom.xpath('//div[@class="bookname"]/h1/text()')[0]
    text = dom.xpath('//div[@id="content"]/text()')
    with open(path + f'{name}.txt', 'w', encoding='utf-8') as f:
        for con in text:
            f.write(con)
    print(f'{name} 下载完成')

def main():
    urls = get_urls()
    for url in urls:
        get_text(url)
        time.sleep(random.randint(1, 3))

if __name__ == '__main__':
    main()

运行效果如下:

程序运行,小说保存到了txt里。

作者:叶庭云 微信公众号:修炼Python CSDN:https://yetingyun.blog.csdn.net/ 本文仅用于交流学习,未经作者允许,禁止转载,更勿做其他用途,违者必究。 觉得文章对你有帮助、让你有所收获的话,期待你的点赞呀,不足之处,也可以在评论区多多指正。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档