zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python爬取书包网文章实战总结

Python 总结 实战 文章 爬取
2023-06-13 09:12:10 时间

大家好,又见面了,我是你们的朋友全栈君。

python爬取书包网文章总结

今天闲来无事去看小说,但是发现没办法直接下载,所以呢就用python爬虫来下载一波了,哈哈…

爬取的是这篇小说:剑破九天(是不是很霸气,话不多说,开始…)

总体思路步骤分为以下三步: 1.获得文章的每个章节链接地址 2.获得章节内容 3.保存到指定位置

首先,进入到自己想要下载小说的网址,按F12进入开发者工具,然后

单击这个然后在原网页点击章节列表即可发现以下数据:

接下来就是提取这个章节的url了,我是用的xpath,当然也可以用正则和bs4,如下代码 book_list = res.xpath('//div[@class="wp b2 info_chapterlist"]/ul/li') 此时book_list中就可以得到所有章节的url了(第一步完)

第二步就是获得章节具体内容了: 和第一步相似,用xpath即得到章节名和其中一章节内容 章节名称:name = res.xpath('//h1/text()') 章节内容:message_list = res.xpath('//dd[@id="contents"]/text()')

获得了自己需要的章节内容后就要进入第三步的保存了,不过在一开始保存时在100章左右时用以下代码出现了UnicodeEncodeError这个问题

    for m in message:
        with open("D:\英雄时刻\{name}.txt".format(name="剑破九天"),"a") as f:
            f.write(m)

然后发现是默认编码方式问题,其默认为gbk,所以需要改成“utf-8”的格式,代码如下:

    for m in message:
        with open("D:\英雄时刻\{name}.txt".format(name="剑破九天"),"a",encoding="utf-8") as f:
            f.write(m)

然后就可以喝一杯茶慢慢等爬取完成了,哈哈,以下为代码:

#剑破九天.text

import requests
import json
from lxml import html


def get_booklist(n):#获得章节地址
    url = "https://www.bookbao99.net/book/201706/05/id_XNTc5MDg2.html"
    header = { 
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
    response = requests.get(url,headers = header)
    response.encoding = "utf-8"
    res = html.fromstring(response.text)
    book_list = res.xpath('//div[@class="wp b2 info_chapterlist"]/ul/li')
    print(len(book_list))#章节个数
    for book in book_list:#遍历所有章节
        try:
            t = book.xpath('a/@href')
            book_url = "https://www.bookbao99.net" + t[0]
            get_message(book_url)
            print("第{n}章爬取完毕".format(n=n))
            n += 1
        except UnicodeEncodeError:
            print("出现一个错误")
        continue


def get_message(url):#提取每个章节内容
    header = { 
   
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"}
    response = requests.get(url,headers = header)
    response.encoding = "utf-8"
    res = html.fromstring(response.text)
    name = res.xpath('//h1/text()')
    n = '\n'+name[0]+'\n\n'
    #print(name[0])
    message_list = res.xpath('//dd[@id="contents"]/text()')
    message_list.insert(0,n)
    #print(message_list)
    save_book(message_list)


def save_book(message):#保存
    for m in message:
        with open("D:\英雄时刻\{name}.txt".format(name="剑破九天"),"a",encoding="utf-8") as f:
            f.write(m)


if __name__ == "__main__":
    n = 1
    get_booklist(n)

是不是美滋滋。 最后呢,欢迎一起讨论爬虫哟~~~

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/148487.html原文链接:https://javaforall.cn